Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

#!/usr/bin/env python 

 

""" 

@file ion/agents/instrumentagents/instrument_agent.py 

@author Steve Foley 

@author Edward Hunter 

@brief Instrument Agent and client classes. 

""" 

 

 

import os 

from uuid import uuid4 

 

from twisted.internet import defer, reactor 

try: 

    import json 

except: 

    import simplejson as json 

 

import ion.util.procutils as pu 

import ion.util.ionlog 

from ion.core.process.process import Process 

from ion.core.process.process import ProcessClient 

from ion.core.process.process import ProcessFactory 

from ion.core.process.process import ProcessDesc 

from ion.services.dm.distribution.events import InfoLoggingEventPublisher 

from ion.services.dm.distribution.events \ 

    import BusinessStateModificationEventPublisher 

from ion.services.dm.distribution.events import DataBlockEventPublisher 

from ion.agents.instrumentagents.instrument_fsm import InstrumentFSM 

from ion.agents.instrumentagents.instrument_constants import AgentParameter, \ 

    AgentConnectionState, AgentState, driver_client, \ 

    DriverAnnouncement, InstErrorCode, DriverParameter, DriverChannel, \ 

    ObservatoryState, DriverStatus, InstrumentCapability, DriverCapability, \ 

    MetadataParameter, AgentCommand, Datatype, TimeSource, ConnectionMethod, \ 

    AgentEvent, AgentStatus, ObservatoryCapability 

 

log = ion.util.ionlog.getLogger(__name__) 

 

DEBUG_PRINT = True if os.environ.get('DEBUG_PRINT',None) == 'True' else False 

 

""" 

Instrument agent observatory metadata. 

""" 

ci_param_metadata = { 

 

    AgentParameter.EVENT_PUBLISHER_ORIGIN: 

        {MetadataParameter.DATATYPE: Datatype.PUBSUB_ORIGIN, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.FRIENDLY_NAME: 'Event Publisher Origin'}, 

    AgentParameter.TIME_SOURCE: 

        {MetadataParameter.DATATYPE: Datatype.ENUM, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.VALID_VALUES: TimeSource, 

         MetadataParameter.FRIENDLY_NAME: 'Time Source'}, 

    AgentParameter.CONNECTION_METHOD: 

        {MetadataParameter.DATATYPE: Datatype.ENUM, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.VALID_VALUES: ConnectionMethod, 

         MetadataParameter.FRIENDLY_NAME: 'Connection Method'}, 

    AgentParameter.DEFAULT_EXP_TIMEOUT: 

        {MetadataParameter.DATATYPE: Datatype.INT, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.MINIMUM_VALUE: 0, 

         MetadataParameter.UNITS: 'Seconds', 

         MetadataParameter.FRIENDLY_NAME: \ 

            'Default Transaction Expire Timeout'}, 

    AgentParameter.MAX_EXP_TIMEOUT: 

        {MetadataParameter.DATATYPE: Datatype.INT, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.MINIMUM_VALUE: 0, 

         MetadataParameter.UNITS: 'Seconds', 

         MetadataParameter.FRIENDLY_NAME: 'Max Transaction Expire Timeout'}, 

    AgentParameter.MAX_ACQ_TIMEOUT: 

        {MetadataParameter.DATATYPE: Datatype.INT, 

         MetadataParameter.LAST_CHANGE_TIMESTAMP: (0, 0), 

         MetadataParameter.MINIMUM_VALUE: 0, 

         MetadataParameter.UNITS: 'Seconds', 

         MetadataParameter.FRIENDLY_NAME: 'Max Transaction Acquire Timeout'}, 

} 

 

 

class InstrumentAgent(Process): 

    """ 

    A generic ion representation of an instrument as an ION resource. 

    """ 

 

    """ 

    The software version of the instrument agent. 

    """ 

    version = '0.1.0' 

 

    @classmethod 

    def get_version(cls): 

        """ 

        Return the software version of the instrument agent. 

        """ 

        return cls.version 

 

    @defer.inlineCallbacks 

    def plc_init(self): 

        # Initialize base class. 

        Process.plc_init(self) 

 

        # We need a yield in a inlineCallback. 

        yield 

 

        """ 

        The ID of the instrument this agent represents. 

        """ 

        self.instrument_id = self.spawn_args.get('instrument-id', None) 

 

        """ 

        Driver process and client descriptions. Parameter dictionaries 

        used to launch driver processes, and dynamically construct driver 

        client objects. 

        """ 

        self._driver_desc = self.spawn_args.get('driver-desc', None) 

        self._client_desc = self.spawn_args.get('client-desc', None) 

 

        """ 

        The driver config dictionary. Default passed as a spawn arg. 

        """ 

        self._driver_config = self.spawn_args.get('driver-config', None) 

 

        """ 

        The driver process ID. 

        """ 

        self._driver_pid = None 

 

        """ 

        List of old driver processes to be cleaned up. 

        """ 

        self._condemned_drivers = [] 

 

        """ 

        The driver client to communicate with the child driver. 

        """ 

        self._driver_client = None 

 

        """ 

        The PubSub origin for the event publisher that this instrument agent 

        uses to distribute messages related to generic events that it handles. 

        One queue sends all messages, each tagged with an event ID number and 

        the "agent" keyword or channel name if applicable (delimited by "."). 

        If "agent" keyword is used, the publication applies to the agent. If 

        the channel is a "*", the event applies to the instrument as a whole or 

        all channels on the instrument 

        For example: 3003.chan1.machine_example_org_14491.357 

        @see    ion/services/dm/distribution/events.py 

        @see    https://confluence.oceanobservatories.org/display/ 

                syseng/CIAD+DM+SV+Notifications+and+Events 

        """ 

        self.event_publisher_origin = str(self.id) 

 

        """ 

        The PubSub publisher for informational/log events. These include 

        agent op errors, transaction events, driver state changes, driver 

        and agent config changes. 

        """ 

        self._log_publisher = \ 

            InfoLoggingEventPublisher(process=self, 

                                      origin=self.event_publisher_origin) 

 

        """ 

        The PubSub publisher for data events 

        """ 

        self._data_publisher = \ 

            DataBlockEventPublisher(process=self, 

                                    origin=self.event_publisher_origin) 

 

        """ 

        The PubSub publisher for agent state change events. 

        """ 

        self._state_publisher = \ 

            BusinessStateModificationEventPublisher(process=self, 

                                    origin=self.event_publisher_origin) 

 

        """ 

        The transducer of the last data received event. Used to publish 

        left over buffer contents on end of a streaming session. 

        """ 

        self._prev_data_transducer = None 

 

        """ 

        A UUID specifying the current transaction. None 

        indicates no current transaction. 

        """ 

        self.transaction_id = None 

 

        """ 

        If a transaction expires during an op_ call, this flag is set so 

        the transaction can be retired when finishing the call. It is handled 

        there to keep the current operation protected until it completes. 

        """ 

        self._transaction_timed_out = False 

 

        """ 

        A twisted delayed function call that implements the transaction 

        timeout. This object allows us to cancel the timeout when the 

        transaction is ended before timeout. 

        """ 

        self._transaction_timeout_call = None 

 

        """ 

        A queue of pending transactions. Start the top one on the list when 

        the current transaction ends. 

        """ 

        self._pending_transactions = [] 

 

        """ 

        An integer in seconds for the maximum allowable timeout to wait for 

        a new transaction. 

        """ 

        self._max_acq_timeout = 60 

 

        """ 

        An integer in seconds for the minimum time a transaction must be open. 

        """ 

        self._min_exp_timeout = 1 

 

        """ 

        An integer in seconds for the default time a transaction may be open. 

        """ 

        self._default_exp_timeout = 300 

 

        """ 

        An integer in seconds giving the maximum allowable time a transaction 

        may be open. 

        """ 

        self._max_exp_timeout = 1800 

 

        """ 

        Upon transaction expire timeout, this flag indicates if the transaction 

        can be immediately retired or should be flagged for retire upon 

        completion of a protected operation. 

        """ 

        self._in_protected_function = False 

 

        """ 

        String indicating the source of time being used for the instrument. 

        See time_sources list for available values. 

        """ 

        self._time_source = TimeSource.NOT_SPECIFIED 

 

        """ 

        String describing how the device is connected to the observatory. 

        See connection_methods list for available values. 

        """ 

        self._connection_method = ConnectionMethod.NOT_SPECIFIED 

 

        """ 

        Buffer to hold instrument data for periodic transmission. 

        """ 

        self._data_buffer = [] 

 

        """ 

        The number of samples to keep in the data buffer before publicaiton. 

        """ 

        self._data_buffer_limit = 0 

 

        """ 

        A dict of device capabilities that is read from the driver upon 

        driver construction. The dict persists whether we are connected to 

        the driver or not. 

        """ 

        self._device_capabilities = {} 

 

        """ 

        List of current alarm conditions. Tuple of (ID, description). 

        """ 

        self._alarms = [] 

 

        """ 

        Dictionary of time status values. 

        """ 

        self._time_status = { 

            'Uncertainty': None, 

            'Peers': None 

        } 

 

        """ 

        Agent state handlers 

        """ 

        self._state_handlers = { 

            AgentState.POWERED_DOWN: self.state_handler_powered_down, 

            AgentState.UNINITIALIZED: self.state_handler_uninitialized, 

            AgentState.INACTIVE: self.state_handler_inactive, 

            AgentState.IDLE: self.state_handler_idle, 

            AgentState.STOPPED: self.state_handler_stopped, 

            AgentState.OBSERVATORY_MODE: self.state_handler_observatory_mode, 

            AgentState.DIRECT_ACCESS_MODE: \ 

                self.state_handler_direct_access_mode 

        } 

 

        """ 

        A finite state machine to track and manage agent state according to 

        the general instrument state model. 

        """ 

        self._fsm = InstrumentFSM(AgentState, AgentEvent, self._state_handlers, 

                                 AgentEvent.ENTER, AgentEvent.EXIT) 

 

        # Set initial state. 

        self._fsm.start(AgentState.UNINITIALIZED) 

 

    ########################################################################### 

    #   State handlers. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def state_handler_powered_down(self, event, params): 

        """ 

        State handler for AgentState.POWERED_DOWN. 

        This is a major state. 

        TODO: Need to investigate use models of POWERED_DOWN. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                                        description=AgentState.POWERED_DOWN) 

            pass 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_uninitialized(self, event, params): 

        """ 

        State handler for AgentState.UNINITIALIZED. 

        Substate of major state AgentState.POWERED_UP. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            # Low level agent initialization beyond construction and plc. 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                                        description=AgentState.UNINITIALIZED) 

            pass 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.INITIALIZE: 

 

            # Initialize: start driver and client and switch to INACTIVE 

            # if successful. 

            self._stop_condemned_drivers() 

            yield self._start_driver() 

            if self._driver_pid: 

                next_state = AgentState.INACTIVE 

 

            else: 

                # Could not initialize error. Set error return value. 

                success = InstErrorCode.AGENT_INIT_FAILED 

 

            pass 

 

        elif event == AgentEvent.RESET: 

            next_state = AgentState.UNINITIALIZED 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_inactive(self, event, params): 

        """ 

        State handler for AgentState.INACTIVE. 

        Substate of major state AgentState.POWERED_UP. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            # Agent initialization beyond driver spawn. 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                                        description=AgentState.INACTIVE) 

 

            # Read the device capabilities. 

            try: 

                self._device_capabilities = {} 

                reply = yield self._driver_client.get_capabilities(\ 

                                                [DriverCapability.DEVICE_ALL]) 

            except: 

                pass 

 

            else: 

                result = reply['result'] 

                for (key, val) in result.iteritems(): 

                    success_val = val[0] 

                    if InstErrorCode.is_ok(success_val): 

                        self._device_capabilities[key] = val 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.RESET: 

            self._stop_driver() 

            if self._driver_pid == None: 

                next_state = AgentState.UNINITIALIZED 

 

            else: 

                success = InstErrorCode.AGENT_DEINIT_FAILED 

 

        elif event == AgentEvent.INITIALIZE: 

            next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.GO_ACTIVE: 

            # Attempt to configure driver. 

            reply = yield self._driver_client.configure(self._driver_config) 

            success = reply['success'] 

 

            # If successful, attempt to connect. 

            if InstErrorCode.is_ok(success): 

                try: 

                    success = None 

                    reply = yield self._driver_client.connect() 

                    success = reply['success'] 

 

                # Exception raised, reply error. 

                except: 

                    success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

                # Command returned, if successful switch state to IDLE. 

                else: 

                    if InstErrorCode.is_ok(success): 

                        next_state = AgentState.IDLE 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_stopped(self, event, params): 

        """ 

        State handler for AgentState.STOPPED. 

        Substate of major state AgentState.ACTIVE. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            # Save agent and driver running state. 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                                        description=AgentState.STOPPED) 

            pass 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.CLEAR: 

            next_state = AgentState.IDLE 

 

        elif event == AgentEvent.RESUME: 

            # Restore agent and driver running state. 

            next_state = AgentState.OBSERVATORY_MODE 

 

        elif event == AgentEvent.GO_INACTIVE: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, if successful switch state to IDLE. 

            else: 

                if InstErrorCode.is_ok(success): 

                    next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.RESET: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, shut down driver. 

            else: 

                if InstErrorCode.is_ok(success): 

                    self._condemn_driver() 

 

                    # If successful, switch to UNINITIALIZED. 

                    if self._driver_pid == None: 

                        next_state = AgentState.UNINITIALIZED 

 

                    # If unsuccessful, switch to inactive. 

                    else: 

                        success = InstErrorCode.AGENT_DEINIT_FAILED 

                        next_state = AgentState.INACTIVE 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_idle(self, event, params): 

        """ 

        State handler for AgentState.IDLE. 

        Substate of major state AgentState.ACTIVE. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            # Clear agent and driver running state. 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                                        description=AgentState.IDLE) 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.GO_INACTIVE: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, if successful switch state to IDLE. 

            else: 

                if InstErrorCode.is_ok(success): 

                    next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.RESET: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, shut down driver. 

            else: 

                if InstErrorCode.is_ok(success): 

                    self._condemn_driver() 

 

                    # If successful, switch to UNINITIALIZED. 

                    if self._driver_pid == None: 

                        next_state = AgentState.UNINITIALIZED 

 

                    # If unsuccessful, switch to inactive. 

                    else: 

                        success = InstErrorCode.AGENT_DEINIT_FAILED 

                        next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.RUN: 

            next_state = AgentState.OBSERVATORY_MODE 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_observatory_mode(self, event, params): 

        """ 

        State handler for AgentState.OBSERVATORY_MODE. 

        Substate of major state AgentState.ACTIVE.RUNNING. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                    description=AgentState.OBSERVATORY_MODE) 

            pass 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.CLEAR: 

            next_state = AgentState.IDLE 

 

        elif event == AgentEvent.PAUSE: 

            next_state = AgentState.STOPPED 

 

        elif event == AgentEvent.GO_DIRECT_ACCESS_MODE: 

            next_state = AgentState.DIRECT_ACCESS_MODE 

 

        elif event == AgentEvent.GO_INACTIVE: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, if successful switch state to IDLE. 

            else: 

                if InstErrorCode.is_ok(success): 

                    next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.RESET: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_DISCONNECT_FAILED 

 

            # Command returned, shut down driver. 

            else: 

                if InstErrorCode.is_ok(success): 

                    #yield pu.asleep(5) 

                    self._condemn_driver() 

                    # If successful, switch to UNINITIALIZED. 

                    if self._driver_pid == None: 

                        next_state = AgentState.UNINITIALIZED 

 

                    # If unsuccessful, switch to inactive. 

                    else: 

                        success = InstErrorCode.AGENT_DEINIT_FAILED 

 

                        next_state = AgentState.INACTIVE 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    @defer.inlineCallbacks 

    def state_handler_direct_access_mode(self, event, params): 

        """ 

        State handler for AgentState.DIRECT_ACCESS_MODE. 

        Substate of major state AgentState.ACTIVE.RUNNING. 

        """ 

 

        yield 

        success = InstErrorCode.OK 

        next_state = None 

        result = None 

        self._debug_print(self._fsm.get_current_state(), event) 

 

        if event == AgentEvent.ENTER: 

            origin = 'agent.%s' % self.event_publisher_origin 

            yield self._state_publisher.create_and_publish_event(origin=origin, 

                            description=AgentState.DIRECT_ACCESS_MODE) 

            pass 

 

        elif event == AgentEvent.EXIT: 

            pass 

 

        elif event == AgentEvent.GO_OBSERVATORY_MODE: 

            next_state = AgentState.OBSERVATORY_MODE 

 

        elif event == AgentEvent.GO_INACTIVE: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, if successful switch state to IDLE. 

            else: 

                if InstErrorCode.is_ok(success): 

                    next_state = AgentState.INACTIVE 

 

        elif event == AgentEvent.RESET: 

            try: 

                reply = yield self._driver_client.disconnect() 

                success = reply['success'] 

 

            # Exception raised, reply error. 

            except: 

                success = InstErrorCode.DRIVER_CONNECT_FAILED 

 

            # Command returned, shut down driver. 

            else: 

                if InstErrorCode.is_ok(success): 

                    self._condemn_driver() 

 

                    # If successful, switch to UNINITIALIZED. 

                    if self._driver_pid == None: 

                        next_state = AgentState.UNINITIALIZED 

 

                    # If unsuccessful, switch to inactive. 

                    else: 

                        success = InstErrorCode.AGENT_DEINIT_FAILED 

                        next_state = AgentState.INACTIVE 

 

        else: 

            success = InstErrorCode.INCORRECT_STATE 

 

        defer.returnValue((success, next_state, result)) 

 

    ########################################################################### 

    #   Transaction Management 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def op_start_transaction(self, content, headers, msg): 

        """ 

        Begin an exclusive transaction with the agent. 

        @param content A dict with None or nonnegative integer values 

            'acq_timeout' and 'exp_timeout' for acquisition and expiration 

            timeouts respectively. 

        @retval A dict with 'success' success/fail string and 

            'transaction_id' transaction ID UUID string. 

        """ 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        acq_timeout = content.get('acq_timeout', None) 

        exp_timeout = content.get('exp_timeout', None) 

        assert(acq_timeout == None or 

               (isinstance(acq_timeout, int) and acq_timeout >= 0)), \ 

            'Expected None or nonnegative int acquisition timeout' 

        assert(exp_timeout == None or 

               (isinstance(exp_timeout, int)) and exp_timeout >= 0), \ 

            'Expected None or nonnegative int expiration timeout' 

 

        result = {'success': None, 'transaction_id': None} 

 

        (success, tid) = yield self._request_transaction(acq_timeout, 

                                        exp_timeout, headers['sender']) 

        result['success'] = success 

        result['transaction_id'] = tid 

 

        # Publish any errors. 

        if InstErrorCode.is_error(success): 

            desc_str = 'Error in op_start_transaction: ' + \ 

                       InstErrorCode.get_string(success) 

            #origin = "agent.%s" % self.event_publisher_origin 

            #yield self._log_publisher.create_and_publish_event(origin=origin, 

            #    description=desc_str) 

 

        else: 

            desc_str = 'opened transaction %s' % tid 

 

        origin = "agent.%s" % self.event_publisher_origin 

        yield self._log_publisher.create_and_publish_event(origin=origin, 

            description=desc_str) 

 

 

 

        yield self.reply_ok(msg, result) 

 

    def _start_transaction(self, exp_timeout): 

        """ 

        Begin an exclusive transaction with the agent. 

        @param exp_timeout An integer in seconds giving the allowable time 

            the transaction may be open. 

        @retval A tuple containing (success/fail, transaction ID UUID string). 

        """ 

 

        assert(exp_timeout == None or 

               (isinstance(exp_timeout, int)) and exp_timeout >= 0), \ 

            'Expected None or nonnegative int expiration timeout' 

 

        # Ensure the expiration timeout is in the valid range. 

        if exp_timeout == None: 

            exp_timeout = self._default_exp_timeout 

        elif exp_timeout > self._max_exp_timeout: 

            exp_timeout = self._max_exp_timeout 

        elif exp_timeout < self._min_exp_timeout: 

            exp_timeout = self._min_exp_timeout 

 

        # If the resource is free, issue a new transaction immediately. 

        if self.transaction_id == None: 

            self.transaction_id = str(uuid4()) 

 

            self._debug_print('started transaction', self.transaction_id) 

 

            # Create and queue up a transaction expiration callback. 

            def transaction_expired(): 

                """ 

                A callback to expire a transaction. Either retire 

                the transaction directly (no protected call running), or set 

                a flag for a protected call to do the cleanup when finishing. 

                """ 

 

                self._debug_print('transaction expired', self.transaction_id) 

 

                self._transaction_timeout_call = None 

                if self._in_protected_function: 

                    self._transaction_timed_out = True 

                else: 

 

                    self._end_transaction(self.transaction_id) 

 

            self._transaction_timeout_call = reactor.callLater(exp_timeout, 

                                                        transaction_expired) 

            return (InstErrorCode.OK, self.transaction_id) 

 

        # Otherwise return locked resource error. 

        else: 

 

            return (InstErrorCode.LOCKED_RESOURCE, None) 

 

    def _request_transaction(self, acq_timeout, exp_timeout, requester): 

        """ 

        @param acq_timeout An integer in seconds to wait to acquire a new 

            transaction. 

        @param exp_timeout An integer in seconds to allow the new transaction 

            to remain open. 

        @param requester A process ID for requester. 

        @retval A deferred that will fire when the a new transaction has 

            been constructed or timeout occurs. The deferred value is a 

            tuple (success/fail, transaction_id). 

        """ 

 

        assert(acq_timeout == None or 

               (isinstance(acq_timeout, int) and acq_timeout >= 0)), \ 

            'Expected None or nonnegative int acquisition timeout' 

        assert(exp_timeout == None or 

               (isinstance(exp_timeout, int)) and exp_timeout >= 0), \ 

            'Expected None or nonnegative int expiration timeout' 

 

        # Ensure the expiration timeout is in the valid range. 

        if exp_timeout == None: 

            exp_timeout = self._default_exp_timeout 

        elif exp_timeout > self._max_exp_timeout: 

            exp_timeout = self._max_exp_timeout 

        elif exp_timeout < self._min_exp_timeout: 

            exp_timeout = self._min_exp_timeout 

 

        # Ensure the acquisition timeout is in the valid range. 

        if acq_timeout == None: 

            acq_timeout = 0 

        elif acq_timeout > self._max_acq_timeout: 

            acq_timeout = self._max_acq_timeout 

 

        d = defer.Deferred() 

 

        # If the resource is free, issue a new transaction immediately. 

        if self.transaction_id == None: 

 

            (success, tid) = self._start_transaction(exp_timeout) 

            d.callback((success, tid)) 

            return d 

 

        else: 

 

            # If resourse not free and no acquisition timeout, return 

            # locked error immediately. 

            if acq_timeout == 0: 

                d.callback((InstErrorCode.LOCKED_RESOURCE, None)) 

                return d 

 

            # If resource not free and there is a valid acquisition timeout, 

            # add the deferred return to the list of pending transactions and 

            # start the acquisition timeout. 

 

            self._debug_print('acquiring transaction') 

 

            def acquisition_timeout(): 

 

                self._debug_print('acquire transaction timed out') 

 

                for item in self._pending_transactions: 

                    if item[0] == d: 

                        self._pending_transactions.remove(item) 

                        d.callback((InstErrorCode.TIMEOUT, None)) 

 

            acq_timeout_call = reactor.callLater(acq_timeout, 

                                        acquisition_timeout) 

 

            self._pending_transactions.append((d, acq_timeout_call, 

                                        exp_timeout, requester)) 

 

            return d 

 

    @defer.inlineCallbacks 

    def op_end_transaction(self, content, headers, msg): 

        """ 

        End the current transaction. 

        @param content A uuid specifying the current transaction to end. 

        @retval success/fail message. 

        """ 

 

        tid = self.transaction_id 

 

        result = self._end_transaction(content) 

 

        # Publish an end transaction message...mainly as a test for now 

        # yield self._log_publisher.create_and_publish_event(\ 

        #                                    name="Transaction ended!") 

 

        # Publish any errors. 

        success = result['success'] 

        if InstErrorCode.is_error(success): 

            desc_str = 'Error in op_end_transaction: ' + \ 

                       InstErrorCode.get_string(success) 

            #origin = "agent.%s" % self.event_publisher_origin 

            #yield self._log_publisher.create_and_publish_event(origin=origin, 

            #    description=desc_str) 

 

        else: 

            desc_str = 'closed transaction %s' % tid 

 

        origin = "agent.%s" % self.event_publisher_origin 

        yield self._log_publisher.create_and_publish_event(origin=origin, 

            description=desc_str) 

 

        yield self.reply_ok(msg, result) 

 

    def _end_transaction(self, tid): 

        """ 

        End the current transaction and start the next pending transaction 

            if one is waiting. 

        @param tid A uuid specifying the current transaction to end. 

        @retval success/fail message. 

        """ 

 

        assert(isinstance(tid, str)), 'Expected a str transaction ID.' 

 

        result = {'success': None} 

 

        if tid == self.transaction_id: 

 

            self._debug_print('ending transaction', self.transaction_id) 

 

            # Remove the current transaction. 

            self.transaction_id = None 

 

            # Reset expiration flag and cancel expiration timeout. 

            self._transaction_timed_out = False 

            if self._transaction_timeout_call != None: 

                self._transaction_timeout_call.cancel() 

                self._transaction_timeout_call = None 

 

            # If there is a pending transaction, issue a new transaction 

            # and cancel the acquisition timeout. 

            if len(self._pending_transactions) > 0: 

                (d, call, exp_timeout, requester) = \ 

                    self._pending_transactions.pop(0) 

                call.cancel() 

                (success, tid) = self._start_transaction(exp_timeout) 

                d.callback((success, tid)) 

 

            # Return success. 

            result['success'] = InstErrorCode.OK 

 

        # If there is no transaction to end, return not locked error. 

        elif self.transaction_id == None: 

            result['success'] = InstErrorCode.RESOURCE_NOT_LOCKED 

 

        # If the tid does not match the current trasaction, return 

        # locked error. 

        else: 

            result['success'] = InstErrorCode.LOCKED_RESOURCE 

 

        return result 

 

    @defer.inlineCallbacks 

    def _verify_transaction(self, tid, optype): 

        """ 

        Verify the passed transaction ID is currently open, or open an 

        implicit transaction. 

        @param tid 'create' to create an implicit transaction, 'none' to 

            perform the operation without a transaction, or a UUID to test 

            against the current transaction ID. 

        @param optype 'get' 'set' or 'execute' 

        @retval True if the transaction is valid or if one was successfully 

            created, False otherwise. 

        """ 

 

        assert(isinstance(tid, str)), 'Expected transaction ID str.' 

        assert(isinstance(optype, str)), 'Expected str optype.' 

 

        success = None 

        if tid != 'create' and tid != 'none' and len(tid) != 36: 

            success = InstErrorCode.INVALID_TRANSACTION_ID 

 

        # Try to start an implicit transaction if tid is 'create' 

        elif tid == 'create': 

            (success, tid) = self._start_transaction(self._default_exp_timeout) 

 

            if InstErrorCode.is_ok(success): 

                success = InstErrorCode.OK 

 

            else: 

                success = InstErrorCode.LOCKED_RESOURCE 

 

        # Allow only gets without a current or created transaction. 

        elif tid == 'none' and self.transaction_id == None and optype == 'get': 

            success = InstErrorCode.OK 

 

        # Otherwise, the given ID must match the outstanding one 

        elif (tid == self.transaction_id): 

            success = InstErrorCode.OK 

 

        else: 

            success = InstErrorCode.LOCKED_RESOURCE 

 

        # Publish any errors. 

        if InstErrorCode.is_error(success): 

            desc_str = 'Error in verify_transaction: ' + \ 

                       InstErrorCode.get_string(success) 

            origin = "agent.%s" % self.event_publisher_origin 

            yield self._log_publisher.create_and_publish_event(origin=origin, 

                description=desc_str) 

 

        defer.returnValue(success) 

 

    ########################################################################### 

    #   Observatory Facing Interface 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def op_hello(self, content, headers, msg): 

 

        # The following line shows how to reply to a message 

        yield self.reply_ok(msg, {'value': 'Hello there, ' + str(content)}, {}) 

 

    @defer.inlineCallbacks 

    def op_execute_observatory(self, content, headers, msg): 

        """ 

        Execute infrastructure commands related to the Instrument Agent 

        instance. This includes commands for messaging, resource management 

        processes, etc. 

        @param content A dict {'command': [command, arg, ,arg], 

            'transaction_id': transaction_id)} 

        @retval ACK message containing a dict 

            {'success': success, 'result': command-specific, 

            'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('command' in content), 'Expected a command.' 

        assert('transaction_id' in content),'Expected a transaction_id.' 

 

        cmd = content['command'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(cmd, (tuple, list))), 'Expected a command \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction. 

        success = yield self._verify_transaction(tid, 'execute') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        success = None 

        result = None 

 

        try: 

            # TRANSITION command. 

            if  cmd[0] == AgentCommand.TRANSITION: 

 

                # Verify required parameter present. 

                if len(cmd) < 2: 

                    success = InstErrorCode.REQUIRED_PARAMETER 

 

                # Verify required parameter valid. 

                elif not AgentEvent.has(cmd[1]): 

                    success = InstErrorCode.INVALID_PARAM_VALUE 

 

                else: 

                    (success, result) = yield self._fsm.on_event_async(cmd[1]) 

 

            # TRANSMIT DATA command. 

            elif cmd[0] == AgentCommand.TRANSMIT_DATA: 

                success = InstErrorCode.NOT_IMPLEMENTED 

 

            # SLEEP command. 

            elif cmd[0] == AgentCommand.SLEEP: 

                if len(cmd) < 2: 

                    success = InstErrorCode.REQUIRED_PARAMETER 

 

                else: 

                    Ltime = cmd[1] 

                    if not isinstance(Ltime, int): 

                        success = InstErrorCode.INVALID_PARAM_VALUE 

 

                    elif Ltime <= 0: 

                        success = InstErrorCode.INVALID_PARAM_VALUE 

                    else: 

                        yield pu.asleep(Ltime) 

                        success = InstErrorCode.OK 

 

            else: 

                success = InstErrorCode.UNKNOWN_COMMAND 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            if success == None: 

                desc_str = 'Error in op_execute_observatory: ' + \ 

                    InstErrorCode.get_string(InstErrorCode.UNKNOWN_ERROR) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            elif InstErrorCode.is_error(success): 

                desc_str = 'Error in op_execute_observatory: ' + \ 

                    InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_observatory(self, content, headers, msg): 

        """ 

        Get data from the cyberinfrastructure side of the agent (registry info, 

        topic locations, messaging parameters, process parameters, etc.) 

        @param content A dict {'params': [param_arg, ,param_arg], 

            'transaction_id': transaction_id}. 

        @retval A reply message containing a dict 

            {'success': success, 'result': {param_arg: (success, val), ..., 

            param_arg: (success, val)}, 'transaction_id': transaction_id) 

        """ 

        self._in_protected_function = True 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

        params = content['params'] 

        tid = content['transaction_id'] 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

        result = {} 

        get_errors = False 

 

        try: 

            # Add each observatory parameter given in params list. 

            for arg in params: 

                if not AgentParameter.has(arg): 

                    result[arg] = (InstErrorCode.INVALID_PARAMETER, None) 

                    get_errors = True 

                    continue 

 

                if arg == AgentParameter.EVENT_PUBLISHER_ORIGIN or \ 

                    arg == AgentParameter.ALL: 

                    if self.event_publisher_origin == None: 

                        result[AgentParameter.EVENT_PUBLISHER_ORIGIN] = \ 

                            (InstErrorCode.OK, None) 

                    else: 

                        result[AgentParameter.EVENT_PUBLISHER_ORIGIN] = \ 

                            (InstErrorCode.OK, self.event_publisher_origin) 

 

                if arg == AgentParameter.DRIVER_DESC or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.DRIVER_DESC] = \ 

                        (InstErrorCode.OK, self._driver_desc) 

 

                if arg == AgentParameter.DRIVER_CLIENT_DESC or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.DRIVER_CLIENT_DESC] = \ 

                        (InstErrorCode.OK, self._client_desc) 

 

                if arg == AgentParameter.DRIVER_CONFIG or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.DRIVER_CONFIG] = \ 

                        (InstErrorCode.OK, self._driver_config) 

 

                if arg == AgentParameter.TIME_SOURCE or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.TIME_SOURCE] = \ 

                        (InstErrorCode.OK, self._time_source) 

 

                if arg == AgentParameter.CONNECTION_METHOD or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.CONNECTION_METHOD] = \ 

                        (InstErrorCode.OK, self._connection_method) 

 

                if arg == AgentParameter.MAX_ACQ_TIMEOUT or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.MAX_ACQ_TIMEOUT] = \ 

                        (InstErrorCode.OK, self._max_acq_timeout) 

 

                if arg == AgentParameter.DEFAULT_EXP_TIMEOUT or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.DEFAULT_EXP_TIMEOUT] = \ 

                        (InstErrorCode.OK, self._default_exp_timeout) 

 

                if arg == AgentParameter.MAX_EXP_TIMEOUT or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.MAX_EXP_TIMEOUT] = \ 

                        (InstErrorCode.OK, self._max_exp_timeout) 

 

                if arg == AgentParameter.BUFFER_SIZE or \ 

                    arg == AgentParameter.ALL: 

                    result[AgentParameter.BUFFER_SIZE] = \ 

                        (InstErrorCode.OK, self._data_buffer_limit) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            if get_errors: 

                success = InstErrorCode.GET_OBSERVATORY_ERR 

 

            else: 

                success = InstErrorCode.OK 

 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_observatory: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            # Transaction clean up. End implicit or expired transactions. 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_set_observatory(self, content, headers, msg): 

        """ 

        Set parameters related to the infrastructure side of the agent 

        (registration information, location, network addresses, etc.) 

        @param content A dict {'params': {param_arg: val, ..., param_arg: val}, 

            'transaction_id': transaction_id}. 

        @retval Reply message with dict 

            {'success': success, 'result': {param_arg: success, ..., 

                param_arg: success}, 'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, dict)), 'Expected a parameter dict.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'set') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

        result = {} 

        set_errors = False 

        set_successes = False 

 

        try: 

 

            # Add each observatory parameter given in params list. 

            # Note: it seems like all the current params should be read only by 

            # general agent users. 

            for arg in params.keys(): 

                if not AgentParameter.has(arg): 

                    result[arg] = InstErrorCode.INVALID_PARAMETER 

                    set_errors = True 

                    continue 

 

                val = params[arg] 

 

                if arg == AgentParameter.DRIVER_DESC: 

                    if not isinstance(val, dict): 

                        # Better checking here. 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

                        set_errors = True 

 

                    else: 

                        self._driver_desc = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                elif arg == AgentParameter.DRIVER_CLIENT_DESC: 

                    if not isinstance(val, dict): 

                        # Better checking here. 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

                        set_errors = True 

 

                    else: 

                        self._client_desc = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                elif arg == AgentParameter.DRIVER_CONFIG: 

                    if not isinstance(val, dict): 

                        # Better checking here. 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

                        set_errors = True 

 

                    else: 

                        self._driver_config = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                elif arg == AgentParameter.TIME_SOURCE: 

                    if TimeSource.has(val): 

                        if val != self._time_source: 

                            self._time_source = val 

                            # Logic here when new time source set. 

                            # And test for successful switch. 

                            result[arg] = InstErrorCode.OK 

                            set_successes = True 

 

                        else: 

                            result[arg] = InstErrorCode.OK 

 

                    else: 

                        set_errors = True 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

                elif arg == AgentParameter.CONNECTION_METHOD: 

                    if ConnectionMethod.has(val): 

                        if val != self._connection_method: 

                            self._connection_method = val 

                            # Logic here when new connection method set. 

                            # And test for successful switch. 

                            result[arg] = InstErrorCode.OK 

                            set_successes = True 

 

                        else: 

                            result[arg] = InstErrorCode.OK 

 

                    else: 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

                elif arg == AgentParameter.MAX_ACQ_TIMEOUT: 

                    if isinstance(val, int) and val >= 0: 

                        self._max_acq_timeout = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                    else: 

                        set_errors = True 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

                elif arg == AgentParameter.DEFAULT_EXP_TIMEOUT: 

                    if isinstance(val, int) and val >= self._min_exp_timeout \ 

                        and val <= self._max_exp_timeout: 

                        self._default_exp_timeout = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                    else: 

                        set_errors = True 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

                elif arg == AgentParameter.MAX_EXP_TIMEOUT: 

                    if isinstance(val, int) and val > self._min_exp_timeout: 

                        self._max_exp_timeout = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                    else: 

                        set_errors = True 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

                elif arg == AgentParameter.BUFFER_SIZE: 

                    if isinstance(val, int) and val >= 0: 

                        self._data_buffer_limit = val 

                        result[arg] = InstErrorCode.OK 

                        set_successes = True 

 

                    else: 

                        set_errors = True 

                        result[arg] = InstErrorCode.INVALID_PARAM_VALUE 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            if set_errors: 

                success = InstErrorCode.GET_OBSERVATORY_ERR 

 

            else: 

                success = InstErrorCode.OK 

 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_set_observatory: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            # Publish the new agent configuration. 

            if set_successes: 

                origin = "agent.%s" % self.event_publisher_origin 

                config = self._get_parameters() 

                # strval = self._get_data_string(config) 

                json_val = json.dumps(config) 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=json_val) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_observatory_metadata(self, content, headers, msg): 

        """ 

        Retrieve metadata about the observatory configuration parameters. 

        @param content A dict 

            {'params': [(param_arg, meta_arg), ..., (param_arg, meta_arg)], 

            'transaction_id': transaction_id} 

        @retval A reply message with a dict {'success': success, 

            'result': {(param_arg, meta_arg): (success, val), ..., 

                (param_arg,meta_arg): (success, val)} 

                'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        try: 

            pass 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            success = InstErrorCode.NOT_IMPLEMENTED 

            reply['success'] = success 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_observatory_metadata: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_observatory_status(self, content, headers, msg): 

        """ 

        Retrieve the observatory status values, including lifecycle state and 

        other dynamic observatory status values indexed by status keys. 

        @param content A dict {'params': [status_arg, ..., status_arg], 

            'transaction_id': transaction_id}. 

        @retval Reply message with a dict 

            {'success': success, 'result': {status_arg: (success, val), ..., 

            status_arg: (success, val)}, 'transaction_id': transaction_id} 

        """ 

 

        self._in_protected_function = True 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

        get_errors = False 

        result = {} 

 

        try: 

 

            # Set up the result message. 

            for arg in params: 

 

                # If status key not recognized, report error. 

                if not AgentStatus.has(arg): 

                    result[arg] = (InstErrorCode.INVALID_STATUS, None) 

                    get_errors = True 

                    continue 

 

                # Agent state. 

                if arg == AgentStatus.AGENT_STATE or arg == AgentStatus.ALL: 

                    result[AgentStatus.AGENT_STATE] = \ 

                        (InstErrorCode.OK, self._fsm.get_current_state()) 

 

                # Connection state. 

                if arg == AgentStatus.CONNECTION_STATE or arg == \ 

                    AgentStatus.ALL: 

                    result[AgentStatus.CONNECTION_STATE] = \ 

                        (InstErrorCode.OK, self._get_connection_state()) 

 

                # Alarm conditions. 

                if arg == AgentStatus.ALARMS or arg == AgentStatus.ALL: 

                    result[AgentStatus.ALARMS] = \ 

                        (InstErrorCode.OK, self._alarms) 

 

                # Time status. 

                if arg == AgentStatus.TIME_STATUS or arg == AgentStatus.ALL: 

                    result[AgentStatus.TIME_STATUS] = \ 

                        (InstErrorCode.OK, self._time_status) 

 

                # Data buffer size. 

                if arg == AgentStatus.BUFFER_SIZE or arg == AgentStatus.ALL: 

                    result[AgentStatus.BUFFER_SIZE] = \ 

                        (InstErrorCode.OK, self._get_buffer_size()) 

 

                # Agent software version. 

                if arg == AgentStatus.AGENT_VERSION or arg == AgentStatus.ALL: 

                    result[AgentStatus.AGENT_VERSION] = \ 

                        (InstErrorCode.OK, self.get_version()) 

 

                # Pending transactions. 

                if arg == AgentStatus.PENDING_TRANSACTIONS or arg == \ 

                    AgentStatus.ALL: 

                    pending_transaction_pids = \ 

                        [item[3] for item in self._pending_transactions] 

                    result[AgentStatus.PENDING_TRANSACTIONS] = \ 

                        (InstErrorCode.OK, pending_transaction_pids) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            if get_errors: 

                success = InstErrorCode.GET_OBSERVATORY_ERR 

            else: 

                success = InstErrorCode.OK 

 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_observatory_status: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_capabilities(self, content, headers, msg): 

        """ 

        Retrieve the agent capabilities, including observatory and 

        device values, both common and specific to the agent / device. 

        @param content A dict {'params': [cap_arg, ..., cap_arg], 

            'transaction_id': transaction_id}. 

        @retval Reply message with a dict {'success': success, 

            'result': {cap_arg: (success, [cap_val, ..., cap_val]), ..., 

            cap_arg: (success, [cap_val, ..., cap_val])}, 

            'transaction_id': transaction_id} 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter list \ 

            or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

        get_errors = False 

        result = {} 

 

        try: 

 

            # Do the work here. 

            # Set up the result message. 

            for arg in params: 

                if not InstrumentCapability.has(arg): 

                    result[arg] = (InstErrorCode.INVALID_CAPABILITY, None) 

                    get_errors = True 

                    continue 

 

                if ObservatoryCapability.has(arg) or arg == \ 

                    InstrumentCapability.ALL: 

 

                    if arg == InstrumentCapability.OBSERVATORY_COMMANDS or \ 

                            arg == InstrumentCapability.OBSERVATORY_ALL or \ 

                            arg == InstrumentCapability.ALL: 

                        result[InstrumentCapability.OBSERVATORY_COMMANDS] = \ 

                            (InstErrorCode.OK, AgentCommand.list()) 

 

                    if arg == InstrumentCapability.OBSERVATORY_PARAMS or \ 

                            arg == InstrumentCapability.OBSERVATORY_ALL or \ 

                            arg == InstrumentCapability.ALL: 

                        result[InstrumentCapability.OBSERVATORY_PARAMS] = \ 

                            (InstErrorCode.OK, AgentParameter.list()) 

 

                    if arg == InstrumentCapability.OBSERVATORY_STATUSES or \ 

                            arg == InstrumentCapability.OBSERVATORY_ALL or \ 

                            arg == InstrumentCapability.ALL: 

                        result[InstrumentCapability.OBSERVATORY_STATUSES] = \ 

                            (InstErrorCode.OK, AgentStatus.list()) 

 

                    if arg == InstrumentCapability.OBSERVATORY_METADATA or \ 

                            arg == InstrumentCapability.OBSERVATORY_ALL or \ 

                            arg == InstrumentCapability.ALL: 

                        result[InstrumentCapability.OBSERVATORY_METADATA] = \ 

                            (InstErrorCode.OK, MetadataParameter.list()) 

 

                if DriverCapability.has(arg) or arg == \ 

                    InstrumentCapability.ALL: 

 

                    if arg == InstrumentCapability.DEVICE_CHANNELS or \ 

                           arg == InstrumentCapability.DEVICE_ALL or \ 

                           arg == InstrumentCapability.ALL: 

                        val = self._device_capabilities.\ 

                              get(InstrumentCapability.DEVICE_CHANNELS, None) 

                        if val != None: 

                            result[InstrumentCapability.DEVICE_CHANNELS] = \ 

                                (InstErrorCode.OK, val) 

                        else: 

                            result[InstrumentCapability.DEVICE_CHANNELS] = \ 

                                (InstErrorCode.INVALID_CAPABILITY, None) 

                            get_errors = True 

 

                    if arg == InstrumentCapability.DEVICE_COMMANDS or \ 

                           arg == InstrumentCapability.DEVICE_ALL or \ 

                           arg == InstrumentCapability.ALL: 

                        val = self._device_capabilities.\ 

                              get(InstrumentCapability.DEVICE_COMMANDS, None) 

                        if val != None: 

                            result[InstrumentCapability.DEVICE_COMMANDS] = \ 

                                (InstErrorCode.OK, val) 

                        else: 

                            result[InstrumentCapability.DEVICE_COMMANDS] = \ 

                                (InstErrorCode.INVALID_CAPABILITY, None) 

                            get_errors = True 

 

                    if arg == InstrumentCapability.DEVICE_METADATA or \ 

                           arg == InstrumentCapability.DEVICE_ALL or \ 

                           arg == InstrumentCapability.ALL: 

                        val = self._device_capabilities.\ 

                              get(InstrumentCapability.DEVICE_METADATA, None) 

                        if val != None: 

                            result[InstrumentCapability.DEVICE_METADATA] = \ 

                                (InstErrorCode.OK, val) 

                        else: 

                            result[InstrumentCapability.DEVICE_METADATA] = \ 

                                (InstErrorCode.INVALID_CAPABILITY, None) 

                            get_errors = True 

 

                    if arg == InstrumentCapability.DEVICE_PARAMS or \ 

                           arg == InstrumentCapability.DEVICE_ALL or \ 

                           arg == InstrumentCapability.ALL: 

                        val = self._device_capabilities.\ 

                              get(InstrumentCapability.DEVICE_PARAMS, None) 

                        if val != None: 

                            result[InstrumentCapability.DEVICE_PARAMS] = \ 

                                (InstErrorCode.OK, val) 

                        else: 

                            result[InstrumentCapability.DEVICE_PARAMS] = \ 

                                (InstErrorCode.INVALID_CAPABILITY, None) 

                            get_errors = True 

 

                    if arg == InstrumentCapability.DEVICE_STATUSES or \ 

                           arg == InstrumentCapability.DEVICE_ALL or \ 

                           arg == InstrumentCapability.ALL: 

                        val = self._device_capabilities.\ 

                              get(InstrumentCapability.DEVICE_STATUSES, None) 

                        if val != None: 

                            result[InstrumentCapability.DEVICE_STATUSES] = \ 

                                (InstErrorCode.OK, val) 

                        else: 

                            result[InstrumentCapability.DEVICE_STATUSES] = \ 

                                (InstErrorCode.INVALID_CAPABILITY, None) 

                            get_errors = True 

 

        # Unkonwn error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            if get_errors: 

                success = InstErrorCode.GET_OBSERVATORY_ERR 

            else: 

                success = InstErrorCode.OK 

 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_observatory_capabilities: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    ########################################################################### 

    #   Instrument Facing Interface 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def op_execute_device(self, content, headers, msg): 

        """ 

        Execute a command on the device fronted by the agent. Commands may be 

        common or specific to the device, with specific commands known through 

        knowledge of the device or a previous get_capabilities query. 

        @param content A dict 

            {'channels': [chan_arg, ..., chan_arg], 

            'command': [command, arg, ..., argN], 

            'transaction_id': transaction_id} 

        @retval A reply message with a dict 

            {'success': success, 

            'result': {chan_arg: (success, command_specific), 

            ..., chan_arg: (success, command_specific_values)}, 

            'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('channels' in content), 'Expected channels.' 

        assert('command' in content), 'Expected command.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        channels = content['channels'] 

        command = content['command'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(channels, (tuple, list))), 'Expected a channels \ 

            list or tuple.' 

        assert(isinstance(command, (tuple, list))), 'Expected a command list \ 

            or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'execute') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.OBSERVATORY_MODE: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_result = yield self._driver_client.execute(channels, command, 

                                                          timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_execute_device: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin\ 

                                            =origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_device(self, content, headers, msg): 

        """ 

        Get configuration parameters from the instrument. 

        @param content A dict {'params': [(chan_arg, param_arg), ..., 

            (chan_arg, param_arg)], 'transaction_id': transaction_id} 

        @retval A reply message with a dict 

            {'success': success, 

            'result': {(chan_arg, param_arg): (success, val), 

            ..., (chan_arg, param_arg): (success, val)}, 

            'transaction_id': transaction_id} 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.OBSERVATORY_MODE and \ 

                          agent_state != AgentState.IDLE and \ 

                          agent_state != AgentState.STOPPED: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_result = yield self._driver_client.get(params,timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

            #pass 

 

        # Unkonwn error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

            #reply['success'] = InstErrorCode.OK 

            #reply['result'] = {'parameter': (InstErrorCode.OK, 'value')} 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_device: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_set_device(self, content, headers, msg): 

        """ 

        Set parameters to the instrument side of of the agent. 

        @param content A dict {'params': {(chan_arg, param_arg): val, ..., 

            (chan_arg, param_arg): val}, 'transaction_id': transaction_id}. 

        @retval Reply message with a dict 

            {'success': success, 'result': {(chan_arg, param_arg): success, 

            ..., chan_arg, param_arg): success}, 

            'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, dict)), 'Expected a parameter dict.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'set') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.OBSERVATORY_MODE: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_result = yield self._driver_client.set(params,timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_execute_device: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_execute_device_direct(self, content, headers, msg): 

        """ 

        Execute untranslated byte data commands on the device. 

        Must be in direct access mode. 

        @param content A dict {'bytes': bytes} 

        @retval A dict {'success': success, 'result': result}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('bytes' in content), 'Expected bytes.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        bytes = content['bytes'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(bytes, str)), 'Expected a bytes string.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'execute') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.DIRECT_ACCESS_MODE: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_result = yield self._driver_client.execute_direct(bytes, 

                                                                  timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKOWN_ERROR 

            raise 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_execute_device_direct: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_device_metadata(self, content, headers, msg): 

        """ 

        Retrieve metadata for the device, its transducers and parameters. 

        @param content A dict {'params': [(chan_arg, param_arg, meta_arg), ..., 

            (chan_arg, param_arg, meta_arg)], 'transaction_id': transaction_id} 

        @retval Reply message with a dict 

            {'success': success, 

            'result': {(chan_arg, param_arg, meta_arg): (success, val), 

            ..., chan_arg, param_arg, meta_arg): (success, val)}, 

            'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.OBSERVATORY_MODE and \ 

                          agent_state != AgentState.IDLE and \ 

                          agent_state != AgentState.STOPPED: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_content = {'params': params} 

            dvr_result = yield self._driver_client.get_metadata(dvr_content, 

                                                                timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

 

        # Unkown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_device_metadata: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    @defer.inlineCallbacks 

    def op_get_device_status(self, content, headers, msg): 

        """ 

        Obtain the status of an instrument. This includes non-parameter 

        and non-lifecycle state of the instrument. 

        @param content A dict {'params': [(chan_arg, status_arg), ..., 

            chan_arg, status_arg)], 'transaction_id': transaction_id}. 

        @retval A reply message with a dict 

            {'success': success, 

            'result': {(chan_arg, status_arg): (success, val), ..., 

            (chan_arg, status_arg): (success, val)}, 

            'transaction_id': transaction_id}. 

        """ 

 

        self._in_protected_function = True 

 

        assert(isinstance(content, dict)), 'Expected a dict content.' 

        assert('params' in content), 'Expected params.' 

        assert('transaction_id' in content), 'Expected a transaction_id.' 

 

        params = content['params'] 

        tid = content['transaction_id'] 

 

        assert(isinstance(params, (tuple, list))), 'Expected a parameter \ 

            list or tuple.' 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

 

        reply = {'success': None, 'result': None, 'transaction_id': None} 

 

        # Set up the transaction 

        success = yield self._verify_transaction(tid, 'get') 

        if InstErrorCode.is_error(success): 

            reply['success'] = success 

            yield self.reply_ok(msg, reply) 

            return 

 

        reply['transaction_id'] = self.transaction_id 

 

        agent_state = self._fsm.get_current_state() 

        if agent_state != AgentState.OBSERVATORY_MODE and \ 

                          agent_state != AgentState.IDLE and \ 

                          agent_state != AgentState.STOPPED: 

            reply['success'] = InstErrorCode.INCORRECT_STATE 

            yield self.reply_ok(msg, reply) 

            return 

 

        timeout = 60 

        success = None 

        result = None 

 

        try: 

 

            dvr_content = {'params': params} 

            dvr_result = yield self._driver_client.get_status(dvr_content, 

                                                              timeout) 

            success = dvr_result.get('success', None) 

            result = dvr_result.get('result', None) 

 

        # Unknown error. 

        except: 

            success = InstErrorCode.UNKNOWN_ERROR 

 

        # Set reply values. 

        else: 

            reply['success'] = success 

            reply['result'] = result 

 

        # Publish errors, clean up transaction. 

        finally: 

 

            # Publish any errors. 

            if InstErrorCode.is_error(success): 

                desc_str = 'Error in op_get_device_metadata: ' + \ 

                           InstErrorCode.get_string(success) 

                origin = "agent.%s" % self.event_publisher_origin 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=desc_str) 

 

            if (tid == 'create') or (self._transaction_timed_out == True): 

                self._end_transaction(self.transaction_id) 

            self._in_protected_function = False 

 

        yield self.reply_ok(msg, reply) 

 

    ########################################################################### 

    #   Publishing Methods 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def op_driver_event_occurred(self, content, headers, msg): 

        """ 

        Called by the driver to announce the occurance of an event. The agent 

        take appropriate action including state transitions, data formatting 

        and publication. This method must be called by a child process of the 

        agent. 

        @param content a dict with 'type' and 'transducer' strings and 'value' 

            object. 

        """ 

        log.debug("op_driver_event_occurred begins") 

        assert isinstance(content, dict), 'Expected a content dict.' 

 

        type = content.get('type', None) 

        transducer = content.get('transducer', None) 

        value = content.get('value', None) 

 

        assert isinstance(type, str), 'Expected a type string.' 

        assert isinstance(transducer, str), 'Expected a transducer string.' 

        assert value != None, 'Expected a value.' 

 

        if not (self._is_child_process(headers['sender-name'])): 

            yield self.reply_err(msg, 

                        'driver event occured evoked from a non-child process') 

            return 

 

        # If data received, coordinate buffering and publishing. 

        if type == DriverAnnouncement.DATA_RECEIVED: 

            # Remember the transducer in case we need to transmit at a time 

            # other than these events. 

            self._prev_data_transducer = transducer 

 

            # Get the driver observatory state. 

            key = (DriverChannel.INSTRUMENT, DriverStatus.OBSERVATORY_STATE) 

            reply = yield self._driver_client.get_status([key]) 

            success = reply['success'] 

            result = reply['result'] 

            obs_status = result.get(key, None) 

            json_val = None 

 

            # If in streaming mode, buffer data and publish at intervals. 

            if InstErrorCode.is_ok(success) and obs_status != None: 

                if obs_status[1] == ObservatoryState.STREAMING: 

                    self._data_buffer.append(value) 

                    if len(self._data_buffer) > self._data_buffer_limit: 

                        # strval = self._get_data_string(self._data_buffer) 

                        json_val = json.dumps(self._data_buffer) 

                        self._data_buffer = [] 

 

                # If not in streaming mode, always publish data upon receipt. 

                else: 

                    #strval = self._get_data_string(value) 

                    json_val = json.dumps([value]) 

 

            #if len(strval) > 0: 

            if json_val != None: 

                origin = "%s.%s" % (transducer, self.event_publisher_origin) 

                log.debug("Instrument Agent publishing data: %s on origin: %s", json_val, origin) 

                yield self._data_publisher.create_and_publish_event(\ 

                    origin=origin, data_block=json_val) 

 

        # Driver configuration changed, publish config. 

        elif type == DriverAnnouncement.CONFIG_CHANGE: 

 

            reply = yield self._driver_client.get([(DriverChannel.ALL, 

                                                    DriverParameter.ALL)]) 

            success = reply['success'] 

            result = reply['result'] 

            if InstErrorCode.is_ok(success) and len(result) > 0: 

                str_key_dict = {} 

                for (key, val) in result.iteritems(): 

                    str_key = '%s__%s' % (key[0], key[1]) 

                    str_key_dict[str_key] = val 

                #strval = self._get_data_string(result) 

                json_val = json.dumps(str_key_dict) 

                origin = "%s.%s" % (transducer, self.event_publisher_origin) 

                yield self._log_publisher.create_and_publish_event(origin=\ 

                                            origin, description=json_val) 

 

        elif type == DriverAnnouncement.ERROR: 

            pass 

 

        # If the driver state changed, publish any buffered data remaining. 

        elif type == DriverAnnouncement.STATE_CHANGE: 

            json_val = None 

            if len(self._data_buffer) > 0: 

                #strval = self._get_data_string(self._data_buffer) 

                json_val = json.dumps(self._data_buffer) 

                #if len(strval) > 0: 

                if json_val != None: 

                    origin = "%s.%s" % (self._prev_data_transducer, 

                                        self.event_publisher_origin) 

                    yield self._log_publisher.create_and_publish_event(origin=\ 

                                                origin, description=json_val) 

 

        elif type == DriverAnnouncement.EVENT_OCCURRED: 

            pass 

 

        else: 

            pass 

 

        self._debug_print_driver_event(type, transducer, value) 

 

 

    ########################################################################### 

    #   Driver lifecycle. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def _start_driver(self): 

        """ 

        Spawn the driver and dynamically construct the client from the 

        current description dictionaries. 

        @retval True if both the client and driver were successfully 

            created, False otherwise. 

        """ 

 

        if self._client_desc and \ 

            'module' in self._client_desc  and \ 

            'class' in self._client_desc and \ 

            self._driver_desc and \ 

            'module' in self._driver_desc and \ 

            'class' in self._driver_desc and \ 

            'name' in self._driver_desc: 

            import_str = 'from ' + self._client_desc['module'] + \ 

            ' import ' + self._client_desc['class'] 

 

            # Spawn the driver process. 

            try: 

                proc_desc = ProcessDesc(**(self._driver_desc)) 

                self.temp_proc_desc = proc_desc 

                self._driver_pid = yield self.spawn_child(proc_desc) 

 

            # If the process desc is bad, trap the error and proceed. 

            # Do not construct client or set member objects. 

            except ImportError: 

                pass 

 

            # Process spawn successful, start client, set member objects. 

            else: 

                self._debug_print('started driver', str(self._driver_pid)) 

 

                # Dynamically construct the client object 

                ctor_str = 'driver_client = ' + self._client_desc['class'] + \ 

                    '(proc=self, target=self._driver_pid)' 

 

                try: 

                    exec import_str 

                    exec ctor_str 

 

                # Client import is bad, shutdown driver and exit. 

                except ImportError, NameError: 

                    log.info('Client import was bad, shutting down driver: %s' \ 

                        % NameError) 

                    self._stop_driver() 

 

                # Other error, shutdown driver and raise. 

                except: 

                    self._stop_driver() 

                    raise 

 

                # Driver and client constructed. Set client object. 

                else: 

                    self._driver_client = driver_client 

                    self._debug_print('constructed driver client', 

                                      str(self._driver_client)) 

 

    def _condemn_driver(self): 

        """ 

        Add current driver to a list to be shutdown at a convenient time. 

        Destroy the client object. 

        """ 

 

        if self._driver_pid != None: 

            self._condemned_drivers.append(self._driver_pid) 

            self._driver_pid = None 

            self._driver_client = None 

 

    def _stop_condemned_drivers(self): 

        """ 

        Shutdown any old driver processes. 

        """ 

 

        new_children = [] 

        for item in self.child_procs: 

            if item.proc_id in self._condemned_drivers: 

                self._debug_print('shutting down driver', str(item.proc_id)) 

                self.shutdown_child(item) 

            else: 

                new_children.append(item) 

        self.child_procs = new_children 

 

    def _stop_driver(self): 

        """ 

        Shutdown the driver and driver client processes. 

        """ 

 

        # Shutdown the driver process and remove its reference. 

        if self._driver_pid != None: 

 

            # Add code to correctly shut down the child proc. 

            for item in self.child_procs: 

                if item.proc_id == self._driver_pid: 

                    self._debug_print('shutting down driver', 

                                      str(self._driver_pid)) 

                    self.shutdown_child(item) 

                    self.child_procs.remove(item) 

 

            self._driver_pid = None 

            self._driver_client = None 

 

    ########################################################################### 

    #   Other. 

    ########################################################################### 

 

    def _get_connection_state(self): 

        """ 

        @retval The current connection state of the agent, including 

            connection to a remote-side agent, existence of a driver, 

            and connection to instrument hardware. Should be extended to 

            handle cases where there is a persistent shoreside and 

            intermittant wetside agent component. 

        """ 

 

        curstate = self._fsm.get_current_state() 

 

        if curstate == AgentState.POWERED_DOWN: 

            return AgentConnectionState.POWERED_DOWN 

        elif curstate == AgentState.UNINITIALIZED: 

            return AgentConnectionState.NO_DRIVER 

        elif curstate == AgentState.INACTIVE: 

            return AgentConnectionState.DISCONNECTED 

        elif curstate == AgentState.IDLE: 

            return AgentConnectionState.CONNECTED 

        elif curstate == AgentState.STOPPED: 

            return AgentConnectionState.CONNECTED 

        elif curstate == AgentState.OBSERVATORY_MODE: 

            return AgentConnectionState.CONNECTED 

        elif curstate == AgentState.DIRECT_ACCESS_MODE: 

            return AgentConnectionState.CONNECTED 

        elif curstate == AgentState.UNKNOWN: 

            return AgentConnectionState.UNKOWN 

        else: 

            return AgentConnectionState.UNKOWN 

 

    def _is_child_process(self, name): 

        """ 

        Determine if a process with the given name is a child process 

        @param name The name to test for subprocess-ness 

        @retval True if the name matches a child process name, False otherwise 

        """ 

        log.debug("__is_child_process looking for process '%s' in %s", 

                  name, self.child_procs) 

        found = False 

        for proc in self.child_procs: 

            if proc.proc_name == name: 

                found = True 

                break 

        return found 

 

    def _get_buffer_size(self): 

        """ 

        Return the total size in characters of the data buffer. 

        Assumes the buffer is a list of string data lines. 

        """ 

        return sum(map(lambda x: len(x), self._data_buffer)) 

 

    def _get_data_string(self, data): 

        """ 

        Convert a sample dictionary or list of sample dictionaries into a 

        publishable string value. 

        @param data A dictionary containing an instrument data sample in 

            key-value pairs or a list of such dictionaries representing a 

            buffered set of samples. 

        @retval A string representation of the data to be published. 

        """ 

 

        assert(isinstance(data, (list, tuple, dict))), 'Expected a data dict, \ 

            or a list or tuple of data dicts' 

 

        if isinstance(data, dict): 

            return str(data) 

        else: 

            strval = '' 

            for item in data: 

                strval += str(item) + ',' 

 

            strval = strval[:-1] 

            return strval 

 

    def _get_parameters(self): 

        """ 

        Get a dictionary of agent parameter values. 

        @retval A dict containing the agent parameters as key-value pairs. 

        """ 

 

        params = {} 

        params[AgentParameter.EVENT_PUBLISHER_ORIGIN] = \ 

            self.event_publisher_origin 

        params[AgentParameter.TIME_SOURCE] = self._time_source 

        params[AgentParameter.CONNECTION_METHOD] = self._connection_method 

        params[AgentParameter.MAX_ACQ_TIMEOUT] = self._max_acq_timeout 

        params[AgentParameter.DEFAULT_EXP_TIMEOUT] = self._default_exp_timeout 

        params[AgentParameter.MAX_EXP_TIMEOUT] = self._max_exp_timeout 

        params[AgentParameter.DRIVER_DESC] = self._driver_desc 

        params[AgentParameter.DRIVER_CLIENT_DESC] = self._client_desc 

        params[AgentParameter.DRIVER_CONFIG] = self._driver_config 

        params[AgentParameter.BUFFER_SIZE] = self._data_buffer_limit 

        return params 

 

    def _debug_print_driver_event(self, type, transducer, value): 

        """ 

        Print debug driver events to stdio. 

        @param type String event type. 

        @param transducer String transducer producing the event. 

        @param value Value of the event. 

        """ 

        log.debug('Driver event type: %s, transducer: %s, value: %s', 

                  type, transducer, value) 

 

 

    def _debug_print(self, event=None, value=None): 

        """ 

        Print debug agent events to stdio. 

        @param event String event type. 

        @param value String event value. 

        """ 

        log.debug("Event: %s, value: %s", event, value) 

 

 

class InstrumentAgentClient(ProcessClient): 

    """ 

    Agent client class provides RPC messaging to the agent service. 

    """ 

 

    # Increased rpc timeout for agent operations. 

    default_rpc_timeout = 180 

 

    ########################################################################### 

    #   Transaction Management. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def start_transaction(self, acq_timeout=None, exp_timeout=None): 

        """ 

        Begin an exclusive transaction with the agent. 

        @param acq_timeout An integer in seconds to wait for the transaction. 

        @param exp_timeout An integer in seconds to expire the transaction. 

        @retval Transaction ID UUID string. 

        """ 

 

        assert(acq_timeout is None or isinstance(acq_timeout, int)), \ 

            'Expected int or None acquisition timeout.' 

        assert(exp_timeout is None or isinstance(exp_timeout, int)), \ 

            'Expected int or None expire timeout.' 

 

        params = { 

            'acq_timeout': acq_timeout, 

            'exp_timeout': exp_timeout 

        } 

 

        if acq_timeout is not None and acq_timeout > 0: 

            rpc_timeout = acq_timeout + 10 

            (content, headers, message) = \ 

                yield self.rpc_send('start_transaction', params, 

                                    timeout=rpc_timeout) 

 

        else: 

            (content, headers, message) = \ 

                yield self.rpc_send('start_transaction', params, 

                                    timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)), 'Expected dict result' 

 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def end_transaction(self, tid): 

        """ 

        End the current transaction. 

        @param tid A uuid string specifying the current transaction to end. 

        """ 

        assert(isinstance(tid, str)), 'Expected a transaction_id str.' 

        (content, headers, message) = yield self.rpc_send('end_transaction', 

                                                          tid) 

        #yield pu.asleep(1) 

        assert(isinstance(content, dict)), 'Expected dict result' 

        defer.returnValue(content) 

 

    ########################################################################### 

    #   Observatory Facing Interface. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def hello(self, text='Hi there'): 

        yield self._check_init() 

        (content, headers, msg) = yield self.rpc_send('hello', text) 

        defer.returnValue(str(content)) 

 

    @defer.inlineCallbacks 

    def execute_observatory(self, command, transaction_id): 

        """ 

        Execute infrastructure commands related to the Instrument Agent 

        instance. This includes commands for messaging, resource management 

        processes, etc. 

        @param command A command list [command, arg, ,arg]. 

        @param transaction_id A transaction_id uuid4 or string 'create,' or 

            'none.' 

        @retval Reply dict {'success': success, 'result': command-specific, 

            'transaction_id': transaction_id}. 

        """ 

 

        assert(isinstance(command, list)), 'Expected a command list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'command': command, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('execute_observatory', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_observatory(self, params, transaction_id='none'): 

        """ 

        Get data from the cyberinfrastructure side of the agent (registry info, 

        topic locations, messaging parameters, process parameters, etc.) 

        @param params A paramter list [param_arg, ,param_arg]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval A reply dict {'success': success, 

            'result': {param_arg: (success, val), ..., 

                param_arg: (success, val)},'transaction_id': transaction_id}. 

        """ 

 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_observatory', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def set_observatory(self, params, transaction_id='none'): 

        """ 

        Set parameters related to the infrastructure side of the agent 

        (registration information, location, network addresses, etc.) 

        @param params A parameter-value dict {'params': {param_arg: val, 

            ..., param_arg: val}. 

        @param transaction_id A transaction ID uuid4 or string 'create,' or 

            'none.' 

        @retval Reply dict 

            {'success': success, 

            'result': {param_arg: success, ..., param_arg: success}, 

            'transaction_id': transaction_id}. 

        """ 

        assert(isinstance(params, dict)), 'Expected a parameter-value dict.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('set_observatory', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_observatory_metadata(self, params, transaction_id='none'): 

        """ 

        Retrieve metadata about the observatory configuration parameters. 

        @param params A metadata parameter list [(param_arg, meta_arg), ..., 

            (param_arg, meta_arg)]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval A reply dict {'success': success, 

            'result': {(param_arg, meta_arg): (success, val), ..., 

                (param_arg, meta_arg): (success, val)}, 

            'transaction_id': transaction_id}. 

        """ 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_observatory_metadata', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_observatory_status(self, params, transaction_id='none'): 

        """ 

        Retrieve the observatory status values, including lifecycle state 

        and other dynamic observatory status values indexed by status keys. 

        @param params A parameter list [status_arg, ..., status_arg]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval Reply dict 

            {'success': success, 'result': {status_arg: (success, val), ..., 

                status_arg: (success, val)}, 'transaction_id': transaction_id} 

        """ 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_observatory_status', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_capabilities(self, params, transaction_id='none'): 

        """ 

        Retrieve the agent capabilities, including observatory and 

        device values, both common and specific to the agent / device. 

        @param params A parameter list [cap_arg, ..., cap_arg]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval Reply dict {'success': success, 

            'result': {cap_arg: (success, val), ...,cap_arg: (success, val)}, 

            'transaction_id': transaction_id} 

        """ 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_capabilities', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    ########################################################################### 

    #   Instrument Facing Interface. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def execute_device(self, channels, command, transaction_id='none'): 

        """ 

        Execute a command on the device fronted by the agent. Commands may be 

        common or specific to the device, with specific commands known through 

        knowledge of the device or a previous get_capabilities query. 

        @param channels A channels list [chan_arg, ..., chan_arg]. 

        @param command A command list [command, arg, ..., argN]). 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval A reply dict 

            {'success': success, 

            'result': {chan_arg: (success, command_specific_values), 

            ..., chan_arg: (success, command_specific_values)}, 

            'transaction_id': transaction_id}. 

        """ 

        assert(isinstance(channels, list)), 'Expected a channels list.' 

        assert(isinstance(command, list)), 'Expected a command list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'channels': channels, 'command': command, 

                   'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('execute_device', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_device(self, params, transaction_id='none'): 

        """ 

        Get configuration parameters from the instrument. 

        @param params A parameters list [(chan_arg, param_arg), ..., 

            (chan_arg, param_arg)]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval A reply dict 

            {'success': success, 

            'result': {(chan_arg, param_arg): (success, val), 

            ..., (chan_arg, param_arg): (success, val)}, 

            'transaction_id': transaction_id} 

        """ 

 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_device', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def set_device(self, params, transaction_id='none'): 

        """ 

        Set parameters to the instrument side of of the agent. 

        @param params A parameter-value dict {(chan_arg, param_arg): val, 

        ..., (chan_arg, param_arg): val}. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval Reply dict 

            {'success': success, 'result': {(chan_arg, param_arg): success, 

            ..., chan_arg, param_arg): success}, 

            'transaction_id': transaction_id}. 

        """ 

        assert(isinstance(params, dict)), 'Expected a parameter-value dict.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('set_device', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_device_metadata(self, params, transaction_id='none'): 

        """ 

        Retrieve metadata for the device, its transducers and parameters. 

        @param params A metadata parameter list 

            [(chan_arg, param_arg, meta_arg), 

                ..., (chan_arg, param_arg, meta_arg)]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval Reply dict 

            {'success': success, 

            'result': {(chan_arg, param_arg, meta_arg): (success, val), ..., 

                (chan_arg, param_arg, meta_arg): (success, val)}, 

            'transaction_id': transaction_id}. 

        """ 

 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_device_metadata', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def get_device_status(self, params, transaction_id='none'): 

        """ 

        Obtain the status of an instrument. This includes non-parameter 

        and non-lifecycle state of the instrument. 

        @param params A parameter list [(chan_arg, status_arg), ..., 

            (chan_arg, status_arg)]. 

        @param transaction_id A transaction ID uuid4 or string 'create,' 

            or 'none.' 

        @retval A reply dict 

            {'success': success, 

            'result': {(chan_arg, status_arg): (success, val), ..., 

                (chan_arg, status_arg): (success, val)}, 

            'transaction_id': transaction_id}. 

        """ 

 

        assert(isinstance(params, list)), 'Expected a parameter list.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'params': params, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('get_device_status', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    @defer.inlineCallbacks 

    def execute_device_direct(self, bytes, transaction_id='none'): 

        """ 

        Execute untranslated byte data commands on the device. 

        Must be in direct access mode and possess the correct 

        transaction_id key for the direct access session. 

        @param bytes An untranslated block of data to send to the device. 

        @param transaction_id A transaction ID uuid4 specifying the 

        direct access session. 

        @retval A reply dict {'success': success, 'result': bytes}. 

        """ 

 

        assert(bytes), 'Expected command bytes.' 

        assert(isinstance(transaction_id, str)), \ 

            'Expected a transaction_id str.' 

 

        yield self._check_init() 

        content = {'bytes': bytes, 'transaction_id': transaction_id} 

        (content, headers, messaage) = yield \ 

            self.rpc_send('execute_device_direct', content, 

                          timeout=self.default_rpc_timeout) 

 

        assert(isinstance(content, dict)) 

        defer.returnValue(content) 

 

    ########################################################################### 

    #   Publishing interface. 

    ########################################################################### 

 

    # op_publish and op_driver_event_occurred are used by the driver 

    # child process and are not invoked through a client. 

 

    ########################################################################### 

    #   Registration interface. 

    ########################################################################### 

 

    @defer.inlineCallbacks 

    def register_resource(self, instrument_id): 

        """ 

        Register the resource. Since this is a subclass, make the appropriate 

        resource description for the registry and pass that into the 

        registration call. 

        """ 

 

        """ 

        ia_instance = InstrumentAgentResourceInstance() 

        ci_params = yield self.get_observatory([driver_address]) 

        ia_instance.driver_process_id = ci_params[driver_address] 

        ia_instance.instrument_ref = ResourceReference( 

            RegistryIdentity=instrument_id, RegistryBranch='master') 

        result = yield ResourceAgentClient.register_resource(self, 

                                                             ia_instance) 

        defer.returnValue(result) 

        """ 

        pass 

 

# Spawn of the process using the module name 

factory = ProcessFactory(InstrumentAgent)