blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
โ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6bc44c153d22405477e6f7e1b5371e21bbff650
|
f532dfc68d8ad1a6e7b8aaf5b7dbc92fbf0efc62
|
/win32_C++/CPPproject/CPP_154p_strtype2.cpp
|
e324a53a13e1d86dd688bf9160f5c71fd40abd36
|
[] |
no_license
|
NamYoonJae/InhaGame
|
691fda687490fb70699f4018ac2888c0b08b5474
|
6e9872436cecccee44f97694f3a047a1d51d86ab
|
refs/heads/main
| 2023-01-19T11:59:35.578386 | 2020-11-26T08:18:34 | 2020-11-26T08:18:34 | 305,272,697 | 0 | 0 | null | null | null | null |
UHC
|
C++
| false | false | 732 |
cpp
|
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void main(void) {
string s1 = "penguin";
string s2, s3;
cout << "string ๊ฐ์ฒด๋ฅผ string ๊ฐ์ฒด์ ๋์
ํ ์ ์๋ค : s2 = s1\n";
s2 = s1;
cout << "s1 : " << s1 << ", s2" << s2 << endl;
cout << "string ๊ฐ์ฒด์ c์คํ์ผ ๋ฌธ์์ด์ ๋์
ํ ์ ์๋ค.\n";
cout << "s2 = \"buzzard\"\n";
cout << "s2 : " << s2 << endl;
cout << "string ๊ฐ์ฒด๋ค์ ๊ฒฐํฉ ํ ์ ์๋ค : s3 = s1 + s2\n";
s3 = s1 + s2;
cout << "s3 :" << s3 << endl;
cout << "string ๊ฐ์ฒด๋ค์ ์ถ๊ฐ ํ ์ ์๋ค.\n";
s1 += s2;
cout << "s1 += s2 ->> s1 = " << s1 << endl;
s2 += "for a day";
cout << "s2 += \"for a day\" --> s2 = " << s2 << endl;
}
|
[
"[email protected]"
] | |
10e549d4ef7234e741eb5cac0b4d27dd3bc88342
|
9ab722e6b9e4ce741cc6f865ba97e0fdc0ad14e5
|
/putty-ng/tab_contents_view_views.h
|
73cd37c0383e065b6b98037fc5b03277b8e12ec2
|
[
"MIT"
] |
permissive
|
csjy309450/PuTTY-ng
|
b892c6474c8ff797f1d0bf555b08351da4fe617b
|
0af73729d45d51936810f675d481c47e5588407b
|
refs/heads/master
| 2022-12-24T13:31:22.786842 | 2020-03-08T16:53:51 | 2020-03-08T16:53:51 | 296,880,184 | 1 | 0 |
MIT
| 2020-09-19T13:54:25 | 2020-09-19T13:54:24 | null |
UTF-8
|
C++
| false | false | 6,286 |
h
|
#ifndef __tab_contents_view_views_h__
#define __tab_contents_view_views_h__
#pragma once
#include "base/memory/scoped_ptr.h"
#include "base/timer.h"
#include "view/widget/widget.h"
#include "native_tab_contents_view_delegate.h"
#include "tab_contents_view.h"
class SkBitmap;
namespace gfx
{
class Point;
class Size;
}
class NativeTabContentsView;
class SadTabView;
// Views-specific implementation of the TabContentsView.
// TODO(beng): Remove last remnants of Windows-specificity, and make this
// subclass Widget.
class TabContentsViewViews : public view::Widget,
public TabContentsView,
public internal::NativeTabContentsViewDelegate
{
public:
// The corresponding TabContents is passed in the constructor, and manages our
// lifetime. This doesn't need to be the case, but is this way currently
// because that's what was easiest when they were split.
explicit TabContentsViewViews(TabContents* tab_contents);
virtual ~TabContentsViewViews();
// Reset the native parent of this view to NULL. Unparented windows should
// not receive any messages.
virtual void Unparent();
NativeTabContentsView* native_tab_contents_view() const
{
return native_tab_contents_view_;
}
// Overridden from TabContentsView:
virtual void CreateView(const gfx::Size& initial_size);
virtual RenderWidgetHostView* CreateViewForWidget(
RenderWidgetHost* render_widget_host);
virtual HWND GetNativeView() const;
virtual HWND GetContentNativeView() const;
virtual HWND GetTopLevelNativeWindow() const;
virtual void GetContainerBounds(gfx::Rect* out) const;
virtual void SetPageTitle(const std::wstring& title);
virtual void OnTabCrashed(base::TerminationStatus status,
int error_code);
virtual void SizeContents(const gfx::Size& size);
virtual void RenderViewCreated(RenderViewHost* host);
virtual void Focus();
virtual void SetInitialFocus();
virtual void StoreFocus();
virtual void RestoreFocus();
virtual void UpdatePreferredSize(const gfx::Size& pref_size);
virtual bool IsDoingDrag() const;
virtual void CancelDragAndCloseTab();
virtual bool IsEventTracking() const;
virtual void CloseTabAfterEventTracking();
virtual void GetViewBounds(gfx::Rect* out) const;
// Implementation of RenderViewHostDelegate::View.
//virtual void CreateNewWindow(
// int route_id,
// const ViewHostMsg_CreateWindow_Params& params);
//virtual void CreateNewWidget(int route_id,
// WebKit::WebPopupType popup_type);
//virtual void CreateNewFullscreenWidget(int route_id);
//virtual void ShowCreatedWindow(int route_id,
// WindowOpenDisposition disposition,
// const gfx::Rect& initial_pos,
// bool user_gesture);
//virtual void ShowCreatedWidget(int route_id,
// const gfx::Rect& initial_pos);
//virtual void ShowCreatedFullscreenWidget(int route_id);
//virtual void ShowContextMenu(const ContextMenuParams& params);
//virtual void ShowPopupMenu(const gfx::Rect& bounds,
// int item_height,
// double item_font_size,
// int selected_item,
// const std::vector<WebMenuItem>& items,
// bool right_aligned);
//virtual void StartDragging(const WebDropData& drop_data,
// WebKit::WebDragOperationsMask operations,
// const SkBitmap& image,
// const gfx::Point& image_offset);
//virtual void UpdateDragCursor(WebKit::WebDragOperation operation);
//virtual void GotFocus();
//virtual void TakeFocus(bool reverse);
private:
// Overridden from internal::NativeTabContentsViewDelegate:
virtual TabContents* GetTabContents() OVERRIDE;
virtual bool IsShowingSadTab() const OVERRIDE;
virtual void OnNativeTabContentsViewShown() OVERRIDE;
virtual void OnNativeTabContentsViewHidden() OVERRIDE;
virtual void OnNativeTabContentsViewSized(const gfx::Size& size) OVERRIDE;
virtual void OnNativeTabContentsViewWheelZoom(bool zoom_in) OVERRIDE;
virtual void OnNativeTabContentsViewMouseDown() OVERRIDE;
virtual void OnNativeTabContentsViewMouseMove(bool motion) OVERRIDE;
virtual void OnNativeTabContentsViewDraggingEnded() OVERRIDE;
virtual view::internal::NativeWidgetDelegate* AsNativeWidgetDelegate()
OVERRIDE;
// Overridden from view::Widget:
virtual view::FocusManager* GetFocusManager() OVERRIDE;
// A helper method for closing the tab.
void CloseTab();
// Windows events ------------------------------------------------------------
// Handles notifying the TabContents and other operations when the window was
// shown or hidden.
void WasHidden();
void WasShown();
// Handles resizing of the contents. This will notify the RenderWidgetHostView
// of the change, reposition popups, and the find in page bar.
void WasSized(const gfx::Size& size);
// TODO(brettw) comment these. They're confusing.
void WheelZoom(int distance);
// ---------------------------------------------------------------------------
// The TabContents whose contents we display.
TabContents* tab_contents_;
// Common implementations of some RenderViewHostDelegate::View methods.
//RenderViewHostDelegateViewHelper delegate_view_helper_;
NativeTabContentsView* native_tab_contents_view_;
// Used to render the sad tab. This will be non-NULL only when the sad tab is
// visible.
SadTabView* sad_tab_;
// The id used in the ViewStorage to store the last focused view.
int last_focused_view_storage_id_;
// The context menu. Callbacks are asynchronous so we need to keep it around.
//scoped_ptr<RenderViewContextMenuViews> context_menu_;
// Set to true if we want to close the tab after the system drag operation
// has finished.
bool close_tab_after_drag_ends_;
// Used to close the tab after the stack has unwound.
base::OneShotTimer<TabContentsViewViews> close_tab_timer_;
// The FocusManager associated with this tab. Stored as it is not directly
// accessible when un-parented.
view::FocusManager* focus_manager_;
DISALLOW_COPY_AND_ASSIGN(TabContentsViewViews);
};
#endif //__tab_contents_view_views_h__
|
[
"[email protected]@b2b8c3b8-ce47-b78c-ec54-380d862a5473"
] |
[email protected]@b2b8c3b8-ce47-b78c-ec54-380d862a5473
|
4d5d87e358f58948a2dc9b9ddd5f63ab76d1d6a9
|
7b8c71aa8c416609ad944a8498d77024dc8d72c8
|
/Animal.cpp
|
a7b200ef6e3a5bf9f7abfcabcc06531f4d995a64
|
[] |
no_license
|
dmesa89/Zoo-Tycoon
|
07164081c5a831effd51e5af0dc85f2b5437f60c
|
3bcccb0bf108d3604903226d36525d88671cdc3f
|
refs/heads/master
| 2020-11-24T17:28:31.377467 | 2019-12-16T00:28:13 | 2019-12-16T00:28:13 | 228,272,691 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,480 |
cpp
|
/******************************************************************************
** Project Name: Zoo Tycoon
** Author: Daniel Mesa
** Date: 10/27/19
** Descriptin: This is a class named Animal.
** It contains a default constructor that initializes data members.
** It also contains It contains accessor and mutator functions
******************************************************************************/
#include "Animal.hpp"
/******************************************************************************
** Animal::Animal()
** It contains a default constructor that initializes data members.
******************************************************************************/
Animal::Animal()
{
name = " ";
age = 0;
cost = 0;
babies = 0;
baseFoodCost = 0.0;
payOff = 0.0;
inZoo = 0;
}
/******************************************************************************
** void Animal::setAge(int days)
**This method sets the age days. it take in an int.
******************************************************************************/
void Animal::setAge(int days)
{age = days;}
/******************************************************************************
** void Animal::addAge(int day)
** This method increments the age. It takes in an int.
******************************************************************************/
void Animal::addAge(int day)
{ age += age;}
/******************************************************************************
** int Animal::getAge()
** This method returns the age.
******************************************************************************/
int Animal::getAge()
{ return age;}
/******************************************************************************
** void Animal::addAge(int day)
** This method sets the cost. It takes in an int.
******************************************************************************/
void Animal::setCost(int startCost)
{ cost = startCost; }
/******************************************************************************
**int Animal::getCost()
** This method returns the cost.
******************************************************************************/
int Animal::getCost()
{ return cost; }
/******************************************************************************
** void Animal::setBabies(int startBabies)
** This method sets the babies. It takes in an int.
******************************************************************************/
void Animal::setBabies(int startBabies)
{ babies = startBabies;}
/******************************************************************************
**int Animal::getBabies()
** This method returns the babies.
******************************************************************************/
int Animal::getBabies()
{ return babies;}
/******************************************************************************
**void Animal::addBabies(int newBabies)
** This method increments the babies
******************************************************************************/
void Animal::addBabies(int newBabies)
{ babies += newBabies; }
/******************************************************************************
**void Animal::setBaseFoodCost(double startFoodCost)
** This method sets the BaseFoodCost. it takes in a double
******************************************************************************/
void Animal::setBaseFoodCost(double startFoodCost)
{ baseFoodCost = startFoodCost; }
/******************************************************************************
**double Animal::getBaseFoodCost()
** This method returns the BaseFoodCost.
******************************************************************************/
double Animal::getBaseFoodCost()
{ return baseFoodCost;}
/******************************************************************************
**void Animal::setPayOff(double startPayOff)
** This method sets the payOff. it takes in a double
******************************************************************************/
void Animal::setPayOff(double startPayOff)
{ payOff = startPayOff;}
/******************************************************************************
**double Animal::getPayOff()
** This method returns the payOff.
******************************************************************************/
double Animal::getPayOff()
{ return payOff;}
/******************************************************************************
*void Animal::setInZoo(bool num)
** This method sets the inZoo. it takes in a bool
******************************************************************************/
void Animal::setInZoo(bool num)
{ inZoo = num; }
/******************************************************************************
*bool Animal::getInZoo()
** This method returns the inZoo.
******************************************************************************/
bool Animal::getInZoo()
{ return inZoo; }
/******************************************************************************
*void Animal::setName(string aName)
** This method sets the name. It takes in a string
******************************************************************************/
void Animal::setName(string aName)
{
name = aName;
}
/******************************************************************************
string Animal::getName()
** This method returns the name.
******************************************************************************/
string Animal::getName()
{
return name;
}
|
[
"[email protected]"
] | |
9ff2e6f8e3066854cb4c2ba6d674d9ae26fcad81
|
90b152fedb88da9d144f244ceaf25da3e85cb9bb
|
/summation.cpp
|
973ab7b96fa5edd394d1f8106316fec1cab58288
|
[] |
no_license
|
franklee26/C-Bureaucracy-
|
4cac9545118c53887ea9e39dbd3c2f307912dee1
|
4420ebdb17ca233e2b08fff4e3e8462991285b12
|
refs/heads/master
| 2020-12-03T00:06:27.544784 | 2017-08-20T08:34:37 | 2017-08-20T08:34:37 | 95,988,002 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 411 |
cpp
|
#include <iostream>
using namespace std;
int n;
void summation(int n);
int main(){
cout<<"Please input your final summation integer:\n";
cin>>n;
cout<<endl;
summation(n);
cout<<endl;
return 0;
}
void summation(int n){
int sum=0;
int i=0;
while (i<=n){
sum=sum+i;
i++;
}
cout<<"The sum from 1 to "<<n<<" is "<<sum<<".";
return;
}
|
[
"[email protected]"
] | |
1644662e00aeb732b7093f5db0aa3bef7aef686c
|
23cb4118d92f2f93398c7fe512f34fa5a0ad9275
|
/SPOT/Actions/ActionLoadPrgReq.h
|
c0c9bbbbaa3cc9eee589f36a143a283bd510ba5b
|
[] |
no_license
|
anasserm/SPOT---CIE202-Project-Code-Framework
|
06d022724eb91039832fd8a9dbe15f8a65eacda8
|
d3f807639a0aeadc981d5af32d081dbd53f515ce
|
refs/heads/main
| 2023-02-17T14:34:43.764385 | 2021-01-20T23:43:49 | 2021-01-20T23:43:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 176 |
h
|
#pragma once
#include "Action.h"
class ActionLoadPrgReq
:
public Action
{
public:
ActionLoadPrgReq(Registrar*);
bool virtual Execute();
virtual ~ActionLoadPrgReq();
};
|
[
"[email protected]"
] | |
5046d1ba82f75fda56a620b346d755b601f02b84
|
7f4b77f95443532f9bed576083879cb24acdc5bc
|
/MapleCode/SmartMouseSource/MiceSensors.cpp
|
2f1a5ce6cba14b81fdd26dbc7ad10106d0c08d33
|
[] |
no_license
|
Nican/SmartMouse
|
6f71d4739ee931389ab20c3bd06d4b90bb834a43
|
356eaa48ffcbd14a5a08dc55232ffffe2345ba90
|
refs/heads/master
| 2016-09-05T10:25:56.794873 | 2012-08-27T14:01:18 | 2012-08-27T14:01:18 | 3,205,232 | 4 | 1 | null | 2012-08-27T14:01:19 | 2012-01-18T02:03:34 |
C++
|
UTF-8
|
C++
| false | false | 235 |
cpp
|
//
// MiceSensors.cpp
//
//
// Created by Alexander Ryan on 4/14/12.
// Copyright 2012 Worcester Polytechnic Institute. All rights reserved.
//
#include "wirish.h"
#include "MiceSensors.h"
void setupMiceSensors(){
return;
}
|
[
"[email protected]"
] | |
11749ae1e537803741af87f65e3d77ca82b296e3
|
bfbdc1e340e72db66b3089d81807ab1383287371
|
/lib/Target/V9/V9FrameLowering.h
|
ea7037b89754c1ba1d371d1bf76a9be2d63c886d
|
[
"NCSA"
] |
permissive
|
LearningOS/llvm-for-alex-cpu-2016
|
df0c6c4da5221bf95c8a7e6d554253170dc5b91c
|
47c56e0f4f2702ce73d642b1daf51853930d1e2b
|
refs/heads/master
| 2020-12-24T22:20:42.979836 | 2016-03-31T07:47:15 | 2016-03-31T07:47:15 | 61,096,731 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,388 |
h
|
//===-- V9FrameLowering.h - Define frame lowering for V9 --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_SPARC_SPARCFRAMELOWERING_H
#define LLVM_LIB_TARGET_SPARC_SPARCFRAMELOWERING_H
#include "V9.h"
#include "llvm/Target/TargetFrameLowering.h"
namespace llvm {
class V9Subtarget;
class V9FrameLowering : public TargetFrameLowering {
public:
explicit V9FrameLowering(const V9Subtarget &ST);
/// emitProlog/emitEpilog - These methods insert prolog and epilog code into
/// the function.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override;
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override;
void
eliminateCallFramePseudoInstr(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const override;
bool hasReservedCallFrame(const MachineFunction &MF) const override;
bool hasFP(const MachineFunction &MF) const override;
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
RegScavenger *RS = nullptr) const override;
int getFrameIndexReference(const MachineFunction &MF, int FI,
unsigned &FrameReg) const override;
/// targetHandlesStackFrameRounding - Returns true if the target is
/// responsible for rounding up the stack frame (probably at emitPrologue
/// time).
bool targetHandlesStackFrameRounding() const override { return true; }
private:
// Remap input registers to output registers for leaf procedure.
void remapRegsForLeafProc(MachineFunction &MF) const;
// Returns true if MF is a leaf procedure.
bool isLeafProc(MachineFunction &MF) const;
// Emits code for adjusting SP in function prologue/epilogue.
void emitSPAdjustment(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
int NumBytes, unsigned ADDrr, unsigned ADDri) const;
};
} // End llvm namespace
#endif
|
[
"[email protected]"
] | |
70d879b717b8d36ae872c4eb76f468441f80119c
|
570ce79e8247aa763761f3e6a46d5220a287fbbc
|
/C++/SourceCode/DataTypes/2/ArrayOne.cpp
|
9cbeab1e8589580eb44480d86f22d60b5c563db5
|
[] |
no_license
|
helloardanish/Competitive-Programming
|
0d6d2a7b825f8397eea94b0a9433ab45b0c28a37
|
29f720454d1bed2be5ee6cd946ffa3b89d68d269
|
refs/heads/master
| 2021-12-01T15:51:40.264549 | 2021-11-29T19:26:35 | 2021-11-29T19:26:35 | 170,266,195 | 1 | 1 | null | 2021-03-02T08:30:14 | 2019-02-12T06:38:49 |
C++
|
UTF-8
|
C++
| false | false | 907 |
cpp
|
#include <iostream>
int main(){
using namespace std;
//first ways
int students[5];
students[0] = 10;
students[1] = 99;
students[2] = 76;
students[3] = 56;
students[4] = 34;
//second ways
int students2[3] = {99,98,99};
cout << "Total marks obtained by first class students " << students[0] + students[1] + students[2] + students[3] + students[4] << ".\n";
cout << "Total marks obtained by second class students " << students2[0] + students2[1] + students2[2] << ".\n";
//checking size of array
cout << "The size of array students is " << sizeof students << " bytes.\n";
cout << "Size of second array is " << sizeof students2 << " bytes.\n";
cout << "Size of one element in first class students " << sizeof students[0] << " bytes.\n";
cout << "Size of one element in second class students " << sizeof students2[0] << " bytes.\n";
return 0;
}
|
[
"[email protected]"
] | |
23da454da0b81508db0a55fe199a9be982d15ecd
|
092dd56a1bf9357466c05d0f5aedf240cec1a27b
|
/tests/libtests/meshio/data/MeshData2D.hh
|
7861f8c6cd542220fef24b6e146d350d9811c31e
|
[
"MIT"
] |
permissive
|
rwalkerlewis/pylith
|
cef02d5543e99a3e778a1c530967e6b5f1d5dcba
|
c5f872c6afff004a06311d36ac078133a30abd99
|
refs/heads/main
| 2023-08-24T18:27:30.877550 | 2023-06-21T22:03:01 | 2023-06-21T22:03:01 | 154,047,591 | 0 | 0 |
MIT
| 2018-10-21T20:05:59 | 2018-10-21T20:05:59 | null |
UTF-8
|
C++
| false | false | 2,002 |
hh
|
// -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2022 University of California, Davis
//
// See LICENSE.md for license information.
//
// ======================================================================
//
#if !defined(pylith_meshio_meshdata2d_hh)
#define pylith_meshio_meshdata2d_hh
#include "MeshData.hh"
namespace pylith {
namespace meshio {
class MeshData2D;
} // pylith
} // meshio
class pylith::meshio::MeshData2D : public MeshData
{
// PUBLIC METHODS ///////////////////////////////////////////////////////
public:
/// Constructor
MeshData2D(void);
/// Destructor
~MeshData2D(void);
// PRIVATE MEMBERS //////////////////////////////////////////////////////
private:
static const int _numVertices; ///< Number of vertices
static const int _spaceDim; ///< Number of dimensions in vertex coordinates
static const int _numCells; ///< Number of cells
static const int _cellDim; ///< Number of dimensions associated with cell
static const int _numCorners; ///< Number of vertices in cell
static const PylithScalar _vertices[]; ///< Pointer to coordinates of vertices
static const int _cells[]; ///< Pointer to indices of vertices in cells
static const int _materialIds[]; ///< Pointer to cell material identifiers
static const int _groups[]; ///< Groups of points
static const int _groupSizes[]; ///< Sizes of groups
static const char* _groupNames[]; ///< Array of group names
static const char* _groupTypes[]; ///< Array of group types
static const int _numGroups; ///< Number of groups
static const bool _useIndexZero; ///< First vertex is 0 if true, 1 if false
};
#endif // pylith_meshio_meshdata2d_hh
// End of file
|
[
"[email protected]"
] | |
f8b7f61de6421b7545756b366ccd6001f51af221
|
6cd1bf6544347c85cabaf672a5ed2dad94a18b63
|
/kakomon/agc032_b.cpp
|
45526ba62ed2318b6161e06d9bfbbc7c9be0604e
|
[] |
no_license
|
Shell-Wataru/AtCoder
|
0a35f12478ac0ab54711171f653ce7bed5189c92
|
0ba32250f4e4a44459a4cd231ff47a5f46c4fe87
|
refs/heads/master
| 2023-01-10T04:21:25.199532 | 2023-01-09T04:16:30 | 2023-01-09T04:16:30 | 89,144,933 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 996 |
cpp
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <iomanip>
#include <numeric>
#include <cmath>
#include <climits>
using namespace std;
using ll = long long;
int solve()
{
ll n;
cin >> n;
vector<pair<ll,ll>> G;
ll pair_value;
if (n % 2 == 1){
pair_value = n;
}else{
pair_value = n + 1;
}
for(int i = 1; i <= n;i++){
for(int j = i+1;j <= n;j++){
if (i+j == pair_value || i == j){
continue;
}else{
G.push_back({i,j});
}
}
}
cout << G.size() << endl;
for(int i = 0;i < G.size();i++){
cout << G[i].first << " " << G[i].second << endl;
}
return 0;
}
int main()
{
// // ๆดๆฐใฎๅ
ฅๅ
// ll t;
// cin >> t;
// for (size_t i = 0; i < t; i++)
// {
solve();
// }
// cout << flush;
return 0;
}
|
[
"[email protected]"
] | |
166435af418796e4ed33a40ae958edce28021d69
|
f01cf0c5aba8a588fefe8a08f0e357b3a023b6dd
|
/Exercise2/ClosestPoint.hh
|
12e3c1ed8bd2ab54b3580e2c587edafb46f88184
|
[] |
no_license
|
Immocat/CS621hw
|
569c6c10e0d8c9f6e674dbe6c87d097c9bd478ca
|
8e92ead1a01000cd6bc8ec778e946dd39e133f8f
|
refs/heads/master
| 2021-05-10T11:01:49.651645 | 2018-04-04T16:52:08 | 2018-04-04T16:52:08 | 118,399,726 | 7 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,277 |
hh
|
//=============================================================================
//
// Code framework for the lecture
//
// "Surface Representation and Geometric Modeling"
//
// Mark Pauly, Mario Botsch, Balint Miklos, and Hao Li
//
// Copyright (C) 2007 by Applied Geometry Group and
// Computer Graphics Laboratory, ETH Zurich
//
//-----------------------------------------------------------------------------
//
// License
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.
//
//=============================================================================
//=============================================================================
//
// CLASS ClosestPoint
//
//=============================================================================
#ifndef CLOSESTPOINT_HPP_
#define CLOSESTPOINT_HPP_
#include <vector>
#include "ANN/ANN.h"
#include "Vector.hh"
/**
* ClosestPoint class
*
* class that allows efficient closest point lookup using KD-tree (ANN library)
*/
class ClosestPoint
{
public:
/// constructor
ClosestPoint();
/// destructor
~ClosestPoint();
/// build ANN KD-tree for _pts
void init(const std::vector< Vector3d > & _pts);
/// release data
void release();
/// retrieve closest point of query
int getClosestPoint(const Vector3d & _queryVertex);
private:
/// data points only used when ANN search is performed
ANNpointArray * dataPoints_;
/// kd tree search structure
ANNkd_tree * kDTree_;
};
#endif /* CLOSESTPOINT_HPP_ */
|
[
"[email protected]"
] | |
90a54ea7bb42786df28ae62590c4b9596c7d0c01
|
68bebfdfbc450b42962eecc316c1d196be8b7bff
|
/LogThread.h
|
1b8ba7cffae00a72effe22b79256405babe9a108
|
[] |
no_license
|
daiybh/LogManager
|
99d396b97b6ebddf3924fc7d385cf12f92d64790
|
838b548097a5c81be169ff52f9bb48dbf0e027ac
|
refs/heads/master
| 2016-09-05T09:25:42.751342 | 2013-08-14T01:35:59 | 2013-08-14T01:35:59 | null | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 1,702 |
h
|
// LogThread.h: interface for the CLogThread class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_LOGTHREAD_H__84A44087_96FD_4A9B_9D1E_2443EED9A98A__INCLUDED_)
#define AFX_LOGTHREAD_H__84A44087_96FD_4A9B_9D1E_2443EED9A98A__INCLUDED_
#ifdef __Win32__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#endif
#include "MsgThread.h"
#include "LogProcess.h"
#include <string>
#include <sys/types.h>
using namespace std;
#define dfWriteWarningLog (0x1) //ๅฏๅจไธไธชๅๆฅๅฟ่ฏทๆฑ
#define dfWriteProcessLog (0x2) //ๅฏๅจไธไธชๅๆฅๅฟ่ฏทๆฑ
#define dfTerminateProcess (0x3) //็ปๆญขๆฌๅค็็บฟ็จ็่ฟ่ก
#define dfWriteStatisticsLog (0x4) //ๅฏๅจไธไธชๅๆฅๅฟ่ฏทๆฑ
#define dfFushLogFile (0x5) //็จ็บฟ็จFLUSHๆฅๅฟๆไปถ
struct LogPara
{
CString strLog;
int nMode;
LogPara()
{
strLog = _T("");
nMode = 1;
}
};
struct StatisticsLogPara
{
char* pLog;
int nLog;
StatisticsLogPara()
{
pLog = NULL;
nLog = 0;
}
};
class CLogThread : public CAkMsgThread
{
public:
CLogThread();
virtual ~CLogThread();
int SetDllName(CString DllName);
int SetSubDllName(CString SubDllName);
LRESULT ThreadMessageProc(UINT uMsg, DWORD dwFlags, LPVOID lpParam, CAkEvent *pEvent);
int FlushToFile();
private:
int _WriteWarningLog(LogPara* pPara);
int _WriteProcessLog(LogPara* pPara);
int _WriteStatisticsLog(StatisticsLogPara* pPara);
int _FlushLogFile(LogPara* pPara);
int _TerminateProcess(BOOL bExtForce);
private:
int m_nLogType;
CLogProcess* m_pLogWriter;
};
#endif // !defined(AFX_LOGTHREAD_H__84A44087_96FD_4A9B_9D1E_2443EED9A98A__INCLUDED_)
|
[
"[email protected]"
] | |
d66f15e2bfb0adc59bc113b1b14610a2c8ff5fe3
|
9247d410d63b76b685d92cdf8ea303fa80693af5
|
/Arch/ExecutorTests.cpp
|
bb69346ef7c4f2cdf5419a39cc09c75f653483ec
|
[] |
no_license
|
Breaktheline/Arch
|
bea72c2eb2e4b006177e00403d25d765ac7fa8a3
|
d8c1c4a4a415927a64f58d9f06f06057560abecf
|
refs/heads/master
| 2021-01-10T20:20:07.504499 | 2012-12-17T19:23:08 | 2012-12-17T19:23:08 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,784 |
cpp
|
#include "gtest/gtest.h"
#include "ArchExecutor.h"
TEST(ExecutorTest, ShouldTestGoodFile)
{
Options* options = new Options();
options->Test = true;
options->Files->Add("Tests/ToDecode/out2.ar");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldTestBadFile)
{
Options* options = new Options();
options->Test = true;
options->Files->Add("Tests/out2_bad.ar");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldListOneCompressedFile)
{
Options* options = new Options();
options->List = true;
options->Files->Add("Tests/ToDecode/out2.ar");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldListOneCompressedFileWithoutPath)
{
Options* options = new Options();
options->List = true;
options->Files->Add("out2");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldListSeveralFiles)
{
Options* options = new Options();
options->List = true;
options->Files->Add("Tests/ToDecode/out2.ar");
options->Files->Add("Tests/ToDecode/out4.ar");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldRecursiveCompressDir)
{
Options* options = new Options();
options->Recursive = true;
options->Dirs->Add("Tests/Dir");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldRecursiveListCompressedDir)
{
Options* options = new Options();
options->Recursive = true;
options->List = true;
options->Dirs->Add("Tests/Dir");
ArchExecutor executor;
executor.Execute(options);
}
TEST(ExecutorTest, ShouldRecursiveDecompressDir)
{
Options* options = new Options();
options->Recursive = true;
options->Decode = true;
options->Dirs->Add("Tests/Dir");
ArchExecutor executor;
executor.Execute(options);
}
|
[
"[email protected]"
] | |
5ab1660765576db373af7f80b6ab6d67de6dcc5e
|
16e54286bb66e4173f746936c829dda2c280ce68
|
/C/OpenJudge/1000-A+B Problem.cpp
|
6340628932f553e2537a5a1924e12159f20eb356
|
[] |
no_license
|
569985011/Work-Space
|
653b932ada697d29178c2211a40d7de7650f9421
|
9afeb1846433d22514a0997b7a48254ce85f5009
|
refs/heads/master
| 2021-05-04T00:28:23.098655 | 2020-09-30T11:32:57 | 2020-09-30T11:32:57 | 71,839,693 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 269 |
cpp
|
#include <stdio.h>
#include <stdlib.h>
/*************************
*ๅ่ฝ๏ผCalculate A+B
*ๆฅ่ช๏ผOpenJudge
*ๆ่ทฏ๏ผ็ผบ็
*ไฝ่
๏ผ[email protected]
*************************/
int main(){
int a,b;
scanf("%d%d",&a,&b);
printf("%d",a+b);
return 0;
}
|
[
"[email protected]"
] | |
dd51d9580596564a4ca3636172b1511dd251aa8a
|
25e1972317eee10c076edab73a440866d44add91
|
/src/asmjs/asm-js.cc
|
157c08db9e4317660fcb14bfa8d17d95855ce26c
|
[
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
] |
permissive
|
Manish-Giri/v8
|
b908802bcd2a949e148b43d32f9e4a84a519c2e4
|
b8cdefb181c2611ba49b1523d306f7485878f4ab
|
refs/heads/master
| 2021-01-23T05:15:01.290632 | 2017-09-04T14:44:33 | 2017-09-05T08:23:56 | 102,463,920 | 0 | 1 | null | 2017-09-05T09:45:02 | 2017-09-05T09:45:02 | null |
UTF-8
|
C++
| false | false | 17,671 |
cc
|
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/asmjs/asm-js.h"
#include "src/asmjs/asm-names.h"
#include "src/asmjs/asm-parser.h"
#include "src/assert-scope.h"
#include "src/ast/ast.h"
#include "src/base/optional.h"
#include "src/base/platform/elapsed-timer.h"
#include "src/compilation-info.h"
#include "src/compiler.h"
#include "src/execution.h"
#include "src/factory.h"
#include "src/handles.h"
#include "src/isolate.h"
#include "src/objects-inl.h"
#include "src/parsing/parse-info.h"
#include "src/parsing/scanner-character-streams.h"
#include "src/parsing/scanner.h"
#include "src/wasm/module-decoder.h"
#include "src/wasm/wasm-js.h"
#include "src/wasm/wasm-module-builder.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-result.h"
namespace v8 {
namespace internal {
const char* const AsmJs::kSingleFunctionName = "__single_function__";
namespace {
enum WasmDataEntries {
kWasmDataCompiledModule,
kWasmDataUsesBitSet,
kWasmDataEntryCount,
};
Handle<Object> StdlibMathMember(Isolate* isolate, Handle<JSReceiver> stdlib,
Handle<Name> name) {
Handle<Name> math_name(
isolate->factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("Math")));
Handle<Object> math = JSReceiver::GetDataProperty(stdlib, math_name);
if (!math->IsJSReceiver()) return isolate->factory()->undefined_value();
Handle<JSReceiver> math_receiver = Handle<JSReceiver>::cast(math);
Handle<Object> value = JSReceiver::GetDataProperty(math_receiver, name);
return value;
}
bool AreStdlibMembersValid(Isolate* isolate, Handle<JSReceiver> stdlib,
wasm::AsmJsParser::StdlibSet members,
bool* is_typed_array) {
if (members.Contains(wasm::AsmJsParser::StandardMember::kInfinity)) {
members.Remove(wasm::AsmJsParser::StandardMember::kInfinity);
Handle<Name> name = isolate->factory()->Infinity_string();
Handle<Object> value = JSReceiver::GetDataProperty(stdlib, name);
if (!value->IsNumber() || !std::isinf(value->Number())) return false;
}
if (members.Contains(wasm::AsmJsParser::StandardMember::kNaN)) {
members.Remove(wasm::AsmJsParser::StandardMember::kNaN);
Handle<Name> name = isolate->factory()->NaN_string();
Handle<Object> value = JSReceiver::GetDataProperty(stdlib, name);
if (!value->IsNaN()) return false;
}
#define STDLIB_MATH_FUNC(fname, FName, ignore1, ignore2) \
if (members.Contains(wasm::AsmJsParser::StandardMember::kMath##FName)) { \
members.Remove(wasm::AsmJsParser::StandardMember::kMath##FName); \
Handle<Name> name(isolate->factory()->InternalizeOneByteString( \
STATIC_CHAR_VECTOR(#fname))); \
Handle<Object> value = StdlibMathMember(isolate, stdlib, name); \
if (!value->IsJSFunction()) return false; \
Handle<JSFunction> func = Handle<JSFunction>::cast(value); \
if (func->shared()->code() != \
isolate->builtins()->builtin(Builtins::kMath##FName)) { \
return false; \
} \
}
STDLIB_MATH_FUNCTION_LIST(STDLIB_MATH_FUNC)
#undef STDLIB_MATH_FUNC
#define STDLIB_MATH_CONST(cname, const_value) \
if (members.Contains(wasm::AsmJsParser::StandardMember::kMath##cname)) { \
members.Remove(wasm::AsmJsParser::StandardMember::kMath##cname); \
Handle<Name> name(isolate->factory()->InternalizeOneByteString( \
STATIC_CHAR_VECTOR(#cname))); \
Handle<Object> value = StdlibMathMember(isolate, stdlib, name); \
if (!value->IsNumber() || value->Number() != const_value) return false; \
}
STDLIB_MATH_VALUE_LIST(STDLIB_MATH_CONST)
#undef STDLIB_MATH_CONST
#define STDLIB_ARRAY_TYPE(fname, FName) \
if (members.Contains(wasm::AsmJsParser::StandardMember::k##FName)) { \
members.Remove(wasm::AsmJsParser::StandardMember::k##FName); \
*is_typed_array = true; \
Handle<Name> name(isolate->factory()->InternalizeOneByteString( \
STATIC_CHAR_VECTOR(#FName))); \
Handle<Object> value = JSReceiver::GetDataProperty(stdlib, name); \
if (!value->IsJSFunction()) return false; \
Handle<JSFunction> func = Handle<JSFunction>::cast(value); \
if (!func.is_identical_to(isolate->fname())) return false; \
}
STDLIB_ARRAY_TYPE(int8_array_fun, Int8Array)
STDLIB_ARRAY_TYPE(uint8_array_fun, Uint8Array)
STDLIB_ARRAY_TYPE(int16_array_fun, Int16Array)
STDLIB_ARRAY_TYPE(uint16_array_fun, Uint16Array)
STDLIB_ARRAY_TYPE(int32_array_fun, Int32Array)
STDLIB_ARRAY_TYPE(uint32_array_fun, Uint32Array)
STDLIB_ARRAY_TYPE(float32_array_fun, Float32Array)
STDLIB_ARRAY_TYPE(float64_array_fun, Float64Array)
#undef STDLIB_ARRAY_TYPE
// All members accounted for.
DCHECK(members.IsEmpty());
return true;
}
void Report(Handle<Script> script, int position, Vector<const char> text,
MessageTemplate::Template message_template,
v8::Isolate::MessageErrorLevel level) {
Isolate* isolate = script->GetIsolate();
MessageLocation location(script, position, position);
Handle<String> text_object = isolate->factory()->InternalizeUtf8String(text);
Handle<JSMessageObject> message = MessageHandler::MakeMessageObject(
isolate, message_template, &location, text_object,
Handle<FixedArray>::null());
message->set_error_level(level);
MessageHandler::ReportMessage(isolate, &location, message);
}
// Hook to report successful execution of {AsmJs::CompileAsmViaWasm} phase.
void ReportCompilationSuccess(Handle<Script> script, int position,
double translate_time, double compile_time,
size_t module_size) {
if (FLAG_suppress_asm_messages || !FLAG_trace_asm_time) return;
EmbeddedVector<char, 100> text;
int length = SNPrintF(
text, "success, asm->wasm: %0.3f ms, compile: %0.3f ms, %" PRIuS " bytes",
translate_time, compile_time, module_size);
CHECK_NE(-1, length);
text.Truncate(length);
Report(script, position, text, MessageTemplate::kAsmJsCompiled,
v8::Isolate::kMessageInfo);
}
// Hook to report failed execution of {AsmJs::CompileAsmViaWasm} phase.
void ReportCompilationFailure(Handle<Script> script, int position,
const char* reason) {
if (FLAG_suppress_asm_messages) return;
Vector<const char> text = CStrVector(reason);
Report(script, position, text, MessageTemplate::kAsmJsInvalid,
v8::Isolate::kMessageWarning);
}
// Hook to report successful execution of {AsmJs::InstantiateAsmWasm} phase.
void ReportInstantiationSuccess(Handle<Script> script, int position,
double instantiate_time) {
if (FLAG_suppress_asm_messages || !FLAG_trace_asm_time) return;
EmbeddedVector<char, 50> text;
int length = SNPrintF(text, "success, %0.3f ms", instantiate_time);
CHECK_NE(-1, length);
text.Truncate(length);
Report(script, position, text, MessageTemplate::kAsmJsInstantiated,
v8::Isolate::kMessageInfo);
}
// Hook to report failed execution of {AsmJs::InstantiateAsmWasm} phase.
void ReportInstantiationFailure(Handle<Script> script, int position,
const char* reason) {
if (FLAG_suppress_asm_messages) return;
Vector<const char> text = CStrVector(reason);
Report(script, position, text, MessageTemplate::kAsmJsLinkingFailed,
v8::Isolate::kMessageWarning);
}
} // namespace
// The compilation of asm.js modules is split into two distinct steps:
// [1] ExecuteJobImpl: The asm.js module source is parsed, validated, and
// translated to a valid WebAssembly module. The result are two vectors
// representing the encoded module as well as encoded source position
// information and a StdlibSet bit set.
// [2] FinalizeJobImpl: The module is handed to WebAssembly which decodes it
// into an internal representation and eventually compiles it to machine
// code.
class AsmJsCompilationJob final : public CompilationJob {
public:
explicit AsmJsCompilationJob(ParseInfo* parse_info, FunctionLiteral* literal,
Isolate* isolate)
: CompilationJob(isolate, parse_info, &compilation_info_, "AsmJs"),
zone_(isolate->allocator(), ZONE_NAME),
compilation_info_(&zone_, isolate, parse_info, literal),
module_(nullptr),
asm_offsets_(nullptr),
translate_time_(0),
compile_time_(0) {}
protected:
Status PrepareJobImpl() final;
Status ExecuteJobImpl() final;
Status FinalizeJobImpl() final;
private:
Zone zone_;
CompilationInfo compilation_info_;
wasm::ZoneBuffer* module_;
wasm::ZoneBuffer* asm_offsets_;
wasm::AsmJsParser::StdlibSet stdlib_uses_;
double translate_time_; // Time (milliseconds) taken to execute step [1].
double compile_time_; // Time (milliseconds) taken to execute step [2].
DISALLOW_COPY_AND_ASSIGN(AsmJsCompilationJob);
};
CompilationJob::Status AsmJsCompilationJob::PrepareJobImpl() {
return SUCCEEDED;
}
CompilationJob::Status AsmJsCompilationJob::ExecuteJobImpl() {
// Step 1: Translate asm.js module to WebAssembly module.
HistogramTimerScope translate_time_scope(
compilation_info()->isolate()->counters()->asm_wasm_translation_time());
size_t compile_zone_start = compilation_info()->zone()->allocation_size();
base::ElapsedTimer translate_timer;
translate_timer.Start();
Zone* compile_zone = compilation_info()->zone();
Zone translate_zone(compilation_info()->isolate()->allocator(), ZONE_NAME);
Utf16CharacterStream* stream = parse_info()->character_stream();
base::Optional<AllowHandleDereference> allow_deref;
if (stream->can_access_heap()) {
DCHECK(
ThreadId::Current().Equals(compilation_info()->isolate()->thread_id()));
allow_deref.emplace();
}
stream->Seek(compilation_info()->literal()->start_position());
wasm::AsmJsParser parser(&translate_zone, stack_limit(), stream);
if (!parser.Run()) {
// TODO(rmcilroy): Temporarily allow heap access here until we have a
// mechanism for delaying pending messages.
DCHECK(
ThreadId::Current().Equals(compilation_info()->isolate()->thread_id()));
AllowHeapAllocation allow_allocation;
AllowHandleAllocation allow_handles;
allow_deref.emplace();
DCHECK(!compilation_info()->isolate()->has_pending_exception());
ReportCompilationFailure(compilation_info()->script(),
parser.failure_location(),
parser.failure_message());
return FAILED;
}
module_ = new (compile_zone) wasm::ZoneBuffer(compile_zone);
parser.module_builder()->WriteTo(*module_);
asm_offsets_ = new (compile_zone) wasm::ZoneBuffer(compile_zone);
parser.module_builder()->WriteAsmJsOffsetTable(*asm_offsets_);
stdlib_uses_ = *parser.stdlib_uses();
size_t compile_zone_size =
compilation_info()->zone()->allocation_size() - compile_zone_start;
size_t translate_zone_size = translate_zone.allocation_size();
compilation_info()
->isolate()
->counters()
->asm_wasm_translation_peak_memory_bytes()
->AddSample(static_cast<int>(translate_zone_size));
translate_time_ = translate_timer.Elapsed().InMillisecondsF();
if (FLAG_trace_asm_parser) {
PrintF(
"[asm.js translation successful: time=%0.3fms, "
"translate_zone=%" PRIuS "KB, compile_zone+=%" PRIuS "KB]\n",
translate_time_, translate_zone_size / KB, compile_zone_size / KB);
}
return SUCCEEDED;
}
CompilationJob::Status AsmJsCompilationJob::FinalizeJobImpl() {
// Step 2: Compile and decode the WebAssembly module.
base::ElapsedTimer compile_timer;
compile_timer.Start();
Handle<HeapNumber> uses_bitset =
compilation_info()->isolate()->factory()->NewHeapNumberFromBits(
stdlib_uses_.ToIntegral());
wasm::ErrorThrower thrower(compilation_info()->isolate(), "AsmJs::Compile");
Handle<WasmModuleObject> compiled =
SyncCompileTranslatedAsmJs(
compilation_info()->isolate(), &thrower,
wasm::ModuleWireBytes(module_->begin(), module_->end()),
compilation_info()->script(),
Vector<const byte>(asm_offsets_->begin(), asm_offsets_->size()))
.ToHandleChecked();
DCHECK(!thrower.error());
compile_time_ = compile_timer.Elapsed().InMillisecondsF();
// The result is a compiled module and serialized standard library uses.
Handle<FixedArray> result =
compilation_info()->isolate()->factory()->NewFixedArray(
kWasmDataEntryCount);
result->set(kWasmDataCompiledModule, *compiled);
result->set(kWasmDataUsesBitSet, *uses_bitset);
compilation_info()->SetAsmWasmData(result);
compilation_info()->SetCode(
BUILTIN_CODE(compilation_info()->isolate(), InstantiateAsmJs));
ReportCompilationSuccess(compilation_info()->script(),
compilation_info()->literal()->position(),
translate_time_, compile_time_, module_->size());
return SUCCEEDED;
}
CompilationJob* AsmJs::NewCompilationJob(ParseInfo* parse_info,
FunctionLiteral* literal,
Isolate* isolate) {
return new AsmJsCompilationJob(parse_info, literal, isolate);
}
MaybeHandle<Object> AsmJs::InstantiateAsmWasm(Isolate* isolate,
Handle<SharedFunctionInfo> shared,
Handle<FixedArray> wasm_data,
Handle<JSReceiver> stdlib,
Handle<JSReceiver> foreign,
Handle<JSArrayBuffer> memory) {
base::ElapsedTimer instantiate_timer;
instantiate_timer.Start();
Handle<HeapNumber> uses_bitset(
HeapNumber::cast(wasm_data->get(kWasmDataUsesBitSet)));
Handle<WasmModuleObject> module(
WasmModuleObject::cast(wasm_data->get(kWasmDataCompiledModule)));
Handle<Script> script(Script::cast(shared->script()));
// TODO(mstarzinger): The position currently points to the module definition
// but should instead point to the instantiation site (more intuitive).
int position = shared->start_position();
// Check that all used stdlib members are valid.
bool stdlib_use_of_typed_array_present = false;
wasm::AsmJsParser::StdlibSet stdlib_uses(uses_bitset->value_as_bits());
if (!stdlib_uses.IsEmpty()) { // No checking needed if no uses.
if (stdlib.is_null()) {
ReportInstantiationFailure(script, position, "Requires standard library");
return MaybeHandle<Object>();
}
if (!AreStdlibMembersValid(isolate, stdlib, stdlib_uses,
&stdlib_use_of_typed_array_present)) {
ReportInstantiationFailure(script, position, "Unexpected stdlib member");
return MaybeHandle<Object>();
}
}
// Check that a valid heap buffer is provided if required.
if (stdlib_use_of_typed_array_present) {
if (memory.is_null()) {
ReportInstantiationFailure(script, position, "Requires heap buffer");
return MaybeHandle<Object>();
}
size_t size = NumberToSize(memory->byte_length());
// TODO(mstarzinger): We currently only limit byte length of the buffer to
// be a multiple of 8, we should enforce the stricter spec limits here.
if (size % FixedTypedArrayBase::kMaxElementSize != 0) {
ReportInstantiationFailure(script, position, "Unexpected heap size");
return MaybeHandle<Object>();
}
// Currently WebAssembly only supports heap sizes within the uint32_t range.
if (size > std::numeric_limits<uint32_t>::max()) {
ReportInstantiationFailure(script, position, "Unexpected heap size");
return MaybeHandle<Object>();
}
} else {
memory = Handle<JSArrayBuffer>::null();
}
wasm::ErrorThrower thrower(isolate, "AsmJs::Instantiate");
MaybeHandle<Object> maybe_module_object =
wasm::SyncInstantiate(isolate, &thrower, module, foreign, memory);
if (maybe_module_object.is_null()) {
DCHECK(!isolate->has_pending_exception());
thrower.Reset(); // Ensure exceptions do not propagate.
ReportInstantiationFailure(script, position, "Internal wasm failure");
return MaybeHandle<Object>();
}
DCHECK(!thrower.error());
Handle<Object> module_object = maybe_module_object.ToHandleChecked();
ReportInstantiationSuccess(script, position,
instantiate_timer.Elapsed().InMillisecondsF());
Handle<Name> single_function_name(
isolate->factory()->InternalizeUtf8String(AsmJs::kSingleFunctionName));
MaybeHandle<Object> single_function =
Object::GetProperty(module_object, single_function_name);
if (!single_function.is_null() &&
!single_function.ToHandleChecked()->IsUndefined(isolate)) {
return single_function;
}
Handle<String> exports_name =
isolate->factory()->InternalizeUtf8String("exports");
return Object::GetProperty(module_object, exports_name);
}
} // namespace internal
} // namespace v8
|
[
"[email protected]"
] | |
ad51acf4b1c351f4217625aa31f7e6ede1980d66
|
e1978ac620c8716b6578ddc357d2fb16014856ae
|
/projects/inclusive_xs/src/common/MCLoader.h
|
6e5e0e95c5a6d44f90ab170d83ac3d962d64f265
|
[] |
no_license
|
stefan-diehl/analysis-projects
|
1deea1ee9323866e60f47da4fc58888e48e1beb3
|
8001e4fa2f643869a92b94f5a05862629e7095b4
|
refs/heads/master
| 2021-08-29T11:10:06.464737 | 2017-12-13T20:38:31 | 2017-12-13T20:38:31 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,909 |
h
|
#ifndef mc_loader_h
#define mc_loader_h
// c++ includes
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// my includes
#include "BaseDISHistograms.h"
#include "h22Reader.h"
#include "HistogramLoader.h"
#include "NathanArchive.h"
#include "Parameters.h"
#include "ParticleFilter.h"
#include "PhysicsEventBuilder.h"
#include "PhysicsEventSelector.h"
#include "CommonTools.h"
#include "PhysicsEvent.h"
#include "StandardHistograms.h"
// root
#include "TLorentzVector.h"
#include "TH2.h"
class MCLoader : public HistogramLoader{
public:
MCLoader(PhysicsEventSelector *eventCriteria, Parameters *pars, std::string outputFile, std::string saveOpts, std::string monteCarloType);
~MCLoader();
protected:
BaseDISHistograms recEvents;
BaseDISHistograms genEvents;
BaseDISHistograms recAndGenEvents;
NathanEIDWrapper eID;
ParticleFilter *filter;
std::string mcType;
StandardHistograms *allRecHistos;
StandardHistograms *passedRecHistos;
StandardHistograms *genHistos;
public:
void Initialize();
void ProcessEvent();
void Save();
void Rebin(int xFactor, int yFactor);
bool EventHasGeneratedElectron();
};
MCLoader::MCLoader(PhysicsEventSelector *eventCriteria, Parameters *pars, std::string outputFile, std::string saveOpts, std::string monteCarloType) : HistogramLoader(eventCriteria, outputFile, saveOpts){
mcType = monteCarloType;
filter = new ParticleFilter(pars);
}
MCLoader::~MCLoader(){
}
void MCLoader::Initialize(){
recEvents.Init(Form("recEvents%s",mcType.c_str()),"Reconstructed MC Hits");
genEvents.Init(Form("genEvents%s",mcType.c_str()),"Generated MC Events");
recAndGenEvents.Init(Form("recAndGenEvents%s",mcType.c_str()),"Rec/Gen Same Bin Events");
// recAndGenEvents.Rebin2D(2,2);
allRecHistos = new StandardHistograms("allRec", 0);
passedRecHistos = new StandardHistograms("passedRec",0);
genHistos = new StandardHistograms("gen", 0);
}
// This is the core routine which conditionally fills histograms.
void MCLoader::ProcessEvent(){
if (EventHasGeneratedElectron()){
// Deal with the generated first.
TLorentzVector genElectron = event.GetGeneratedParticle(11);
PhysicsEvent genPhysicsEvent = builder.getPhysicsEvent(genElectron);
genHistos->Fill(genPhysicsEvent);
// Maybe here we should check that the track was reconstructed
// if (event.gpart > 0), but that would probably skew acceptance
// by stopping all particles which went through holes ect. so it
// doesn't seem like what we want to do.
int mcSector = event.GetMCSectorByPID(11);
// if (mcSector > -1 && mcSector < 7 && eventSelector->get_cut("Relative Phi Cut")->passes(genPhysicsEvent)) {
if (mcSector > -1 && mcSector < 7) {
genEvents.Fill(genPhysicsEvent, mcSector);
}
// Dealing directly with histograms in base histograms here
// is not ideal, think of a better way.
int genxByQQBin = recAndGenEvents.xByQQ[0]->FindBin(genPhysicsEvent.x, genPhysicsEvent.qq);
int genwByQQBin = recAndGenEvents.wByQQ[0]->FindBin(genPhysicsEvent.w, genPhysicsEvent.qq);
// eID.set_info(GetRunNumber(),GSIM);
// int e_index = eID.get_electron(event);
int e_index = filter->getByPID(event, 11);
if (e_index > -123){
TLorentzVector recElectron = event.GetTLorentzVector(e_index, 11);
int sector = event.dc_sect[e_index];
PhysicsEvent recPhysicsEvent = builder.getPhysicsEvent(recElectron);
allRecHistos->Fill(event, e_index, recPhysicsEvent);
// Again doing this to fill coincident events recAndGen needed to calculate purity and
// stability.
int recwByQQBin = recAndGenEvents.wByQQ[0]->FindBin(recPhysicsEvent.w, recPhysicsEvent.qq);
if (eventSelector->passes(recPhysicsEvent) && sector > 0) {
recEvents.Fill(recPhysicsEvent, sector);
passedRecHistos->Fill(event, e_index, recPhysicsEvent);
}
}
} // End of EventHasGeneratedElectron()
}
bool MCLoader::EventHasGeneratedElectron(){
for(int ipart=0; ipart<event.mcnentr; ipart++){
if (event.mcid[ipart] == 11){
return true;
}
}
return false;
}
void MCLoader::Save(){
// You may want to recreate the file, but dont overwrite it by
// doing "RECREATE" on the second 2 saves.
recEvents .Save(outputFilenameWithExtension, saveOption);
genEvents .Save(outputFilenameWithExtension, "UPDATE");
recAndGenEvents.Save(outputFilenameWithExtension, "UPDATE");
TFile *out = new TFile(outputFilenameWithExtension.c_str(),"UPDATE");
allRecHistos ->Save(out);
passedRecHistos->Save(out);
genHistos ->Save(out);
}
void MCLoader::Rebin(int xFactor, int yFactor){
recEvents.Rebin2D(xFactor, yFactor);
genEvents.Rebin2D(xFactor, yFactor);
recAndGenEvents.Rebin2D(xFactor, yFactor);
}
#endif
|
[
"[email protected]"
] | |
58f0062c5ff50dd8445c234ed9c3b3c5454c2557
|
3f7828e6c680391eb73bc43856ba25a9def98726
|
/Background.cpp
|
d1a046a8bba8e6309bb68da2ebb4f37ca8a1534a
|
[] |
no_license
|
yakugama/SpaceShooter
|
4ba7e4d67231858ab267561beedc6fb10a9eec17
|
3e96a45fc105e3d6f7b899556339a0f7a7ed1e39
|
refs/heads/master
| 2020-05-02T16:52:18.471365 | 2019-03-27T22:04:26 | 2019-03-27T22:04:26 | 178,081,059 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,341 |
cpp
|
#include "Background.h"
Background::Background()
{
if (TextureManager::cosmos)
{
this->cosmos = TextureManager::cosmos;
//aflarea inaltimii si latimii
SDL_QueryTexture(cosmos, NULL, NULL, &width, &height);
//Setare coordonate dreptunghi-sursa
srcRect.x = 0;
srcRect.y = 0;
srcRect.h = height;
srcRect.w = width;
//Setare coordonate pt dreptunghiul din ecran
dstRectOnScreen.x = 0;
dstRectOnScreen.y = 0;
dstRectOnScreen.h = height;
dstRectOnScreen.w = width;
//Setare coordonate pt dreptunghiul inafara ecranului
dstRectOffScreen.x = 0;
dstRectOffScreen.y = -height;
dstRectOffScreen.h = height;
dstRectOffScreen.w = width;
speed = 0.3f;
offset = 0.0f;
}
}
Background::~Background()
{
if (cosmos)
{
SDL_DestroyTexture(cosmos);
cosmos = nullptr;
}
}
void Background::Update()
{
if (dstRectOffScreen.y == 0)
{
dstRectOnScreen.y = 0;
dstRectOffScreen.y = -height;
offset = 0.0f;
}
else
{
offset += speed;
//dstRectOffScreen.y = (int)(dstRectOffScreen.y + Yposition);
dstRectOnScreen.y = (int)(offset);
dstRectOffScreen.y = dstRectOnScreen.y - height;
}
}
void Background::Render()
{
TextureManager::Draw(cosmos, srcRect, dstRectOffScreen);
TextureManager::Draw(cosmos, srcRect, dstRectOnScreen);
}
|
[
"[email protected]"
] | |
44d6474ab17ee443a2b41fefa79c9ed113871445
|
0acace81433043d274bbeb5628fc150cc0f2d072
|
/Sources/Emulator/src/mess/machine/c64/cpm.h
|
447af110f3b87956512c77e643544cfcb63f8b68
|
[] |
no_license
|
SonnyJim/MAMEHub
|
b11780c6e022b47b0be97e4670c49b15a55ec052
|
aeaa71c5ebdcf33c06d56625810913a99d3a4a66
|
refs/heads/master
| 2020-12-03T03:36:28.729082 | 2014-07-11T13:04:23 | 2014-07-11T13:04:23 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,658 |
h
|
/**********************************************************************
Commodore 64 CP/M cartridge emulation
Copyright MESS Team.
Visit http://mamedev.org for licensing and usage restrictions.
**********************************************************************/
#pragma once
#ifndef __CPM__
#define __CPM__
#define ADDRESS_MAP_MODERN
#include "emu.h"
#include "cpu/z80/z80.h"
#include "machine/c64/exp.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> c64_cpm_cartridge_device
class c64_cpm_cartridge_device : public device_t,
public device_c64_expansion_card_interface
{
public:
// construction/destruction
c64_cpm_cartridge_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// optional information overrides
virtual machine_config_constructor device_mconfig_additions() const;
// not really public
DECLARE_READ8_MEMBER( dma_r );
DECLARE_WRITE8_MEMBER( dma_w );
protected:
// device-level overrides
virtual void device_start();
virtual void device_reset();
// device_c64_expansion_card_interface overrides
virtual void c64_cd_w(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2);
virtual int c64_game_r(offs_t offset, int sphi2, int ba, int rw, int hiram);
private:
inline void update_signals();
required_device<cpu_device> m_maincpu;
int m_enabled;
int m_ba;
int m_reset;
};
// device type definition
extern const device_type C64_CPM;
#endif
|
[
"[email protected]"
] | |
99dd76b5fb34adec77378c65cc5c34bfbeb53959
|
c9b02ab1612c8b436c1de94069b139137657899b
|
/rpg/app/dbwriter/DBClient.cpp
|
92f0762bffdb63e01e9544e775bb9cfd9df08e12
|
[] |
no_license
|
colinblack/game_server
|
a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab
|
a7724f93e0be5c43e323972da30e738e5fbef54f
|
refs/heads/master
| 2020-03-21T19:25:02.879552 | 2020-03-01T08:57:07 | 2020-03-01T08:57:07 | 138,948,382 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,924 |
cpp
|
#include <stdio.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <fcntl.h>
#include <assert.h>
#include <errno.h>
#include <libgen.h>
#include <stddef.h>
#include "AsyncDBManager.h"
#include "DBClientManager.h"
#include "DBClient.h"
#include "PollThread.h"
#include "Utils.h"
#define CLOSE(fd) {if(fd != 0) close(fd);fd=0;}
CDBClientAsync::CDBClientAsync(CPollThread *o, int fd) {
ownerUnit = o;
netfd = fd;
memset(m_peerAddr, 0, sizeof(m_peerAddr));
Utils::fdinfo(netfd, m_peerAddr, m_peerIp, m_peerPort);
DBClientManager::Instance()->addClient(this);
}
int CDBClientAsync::Attach() {
EnableInput();
if (AttachPoller()) {
return -1;
}
return 0;
}
CDBClientAsync::~CDBClientAsync() {
}
void CDBClientAsync::InputNotify(void) {
recvProcess();
}
void CDBClientAsync::HangupNotify(void) {
errorProcess(SRC_HANGUP);
}
void CDBClientAsync::OutputNotify(void) {
}
int CDBClientAsync::errorProcess(int src) {
DetachPoller();
delete this;
return 0;
}
bool CDBClientAsync::sendData(IBuffer* pData) {
return false;
}
void CDBClientAsync::recvProcess() {
int len = recv(netfd, m_inBuf.GetNativeBuffer() + m_inBuf.GetSize(), m_inBuf.GetFreeCapacity(), 0);
if (len == 0) {
error_log("peer close [%s:%d] fd=%d", m_peerAddr, m_peerPort, netfd);
errorProcess(SRC_INPUT);
return;
} else if (len < 0) {
errorProcess(SRC_INPUT);
return;
}
uint32_t decodeSize = 0;
m_inBuf.SetSize(m_inBuf.GetSize() + len);
DataPacket packet;
do {
packet.Clean();
bool ret = packet.Decode(&m_inBuf);
decodeSize = packet.GetDecodeSize();
if (decodeSize > 0) {
if (!ret) {
error_log("decode error");
decodeSize = 0;
break;
}
m_inBuf.Remove(0, decodeSize);
}
if (ret) {
AsyncDBManager::Instance()->push(packet);
debug_log("%u", packet.body.GetSize());
}
} while (decodeSize > 0);
}
|
[
"[email protected]"
] | |
17b7ae133014dc0aaf87d1a4586b521a18c32a01
|
6ca08dc2de5fe6a74c481389463548412c576418
|
/Homage/MattingLib/UnBackground/UnBlobD.cpp
|
62652e39dc86c5c4c123ac37d38ede0d1dfe0a1a
|
[] |
no_license
|
nirch/homage-cv-app
|
d2e3fbb70d876adc73fe4466f1c39a3fbece21f4
|
60e6a759ac8caf8079af9818e8464c6eda22b0e8
|
refs/heads/master
| 2021-03-24T10:11:55.488542 | 2016-08-03T10:00:47 | 2016-08-03T10:00:47 | 18,877,919 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,374 |
cpp
|
// Defines the entry point for the console application.
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#ifdef _DEBUG
#define _DUMP
#endif
#include "Ulog/Log.h"
#include "ImageType/ImageType.h"
#include "ImageDump/ImageDump.h"
#include "Imagelabel/BwLabel.h"
#include "ImageLabel/ImageLabel.h"
#include "Histogram/Histogram.h"
#include "UnBackground.h"
#include "bImage.h"
int CUnBackground::ProcessBlobD()
{
ProcessBlobD_figure_blob( m_abw, &m_asFigure );
u_char T[6] = { 255, 0, 144, 96, 64 };
image_type *im = imageLabelUI_color_imageT( m_abw, T, NULL );
IMAGE_DUMP_DUP( im, 8, 1, "ub", 1, "DM-3" );
image_destroy( im, 1 );
m_apt = ProcessBlobD_point( m_abw, m_apt );
PT2DA_DUMP( m_apt, "ub", 1, "DM-3" );
return( 1 );
}
int CUnBackground::ProcessBlobD_figure_blob( imageLabel_type *abw, sbA_type *as )
{
int i, j;
u_int *bp = abw->im->data_ui;
for( i = 0 ; i < abw->im->height ; i++ ){
int j0, j1;
if(as->a[i].j0 == -1 && as->a[i].j1 == -1)
continue;
j0 = ( as->a[i].j0 < 0 )? 0 : as->a[i].j0;
j1 = ( as->a[i].j1 < 0 )? abw->im->width : as->a[i].j1;
u_int *sp = (u_int *)IMAGE_PIXEL( abw->im, i, j0 );
for( j = j0 ; j < j1 ; j++, sp++ ){
bwLabel_type *bw = &abw->a[*sp];
if( bw->color == 0 ) continue;
if( bw->color > 2 ) continue;
bw->color += 2;
}
}
return( 1 );
}
pt2dA_type * CUnBackground::ProcessBlobD_point( imageLabel_type *abw, pt2dA_type *apt )
{
int i, j;
apt = pt2dA_realloc( apt, abw->im->width * abw->im->height/4 );
u_char T[] = { 0, 1, 1, 0, 0, 0 };
m_imMask = imageLabelUI_color_imageT( m_abw, T, m_imMask );
for( i = 2 ; i < m_imMask->height-1 ; i += 4 ){
u_char *sp = (u_char *)IMAGE_PIXEL( m_imMask, i, 2 );
sp -= 1;
u_char *sp0 = sp - abw->im->width;
u_char *sp1 = sp + abw->im->width;
for( j = 2 ; j < m_imMask->width-1 ; j += 4, sp += 4, sp1 += 4, sp0 += 4 ){
// if( *sp != 1 && *sp != 2 ) continue;
int n = ( sp0[0] + sp0[1] + sp0[2] +
sp[0] + sp[1] + sp[2] +
sp1[0] + sp1[1] + sp1[2] );
if( n < 9 ) continue;
pt2d_type *pt = &apt->a[apt->nA++];
pt->p.x = ( j+0.5)*8;
pt->p.y = ( i+0.5)*8;
}
}
return( apt );
}
|
[
"[email protected]"
] | |
4c531343574d5ea664b1a494707a78bcee129a6b
|
1b0d8c051ca6482dd3c2cbf5d7cf6dff1a1220db
|
/project/code/src/main.cpp
|
c4185dcd5a5265c928ff76b46871127220232976
|
[
"Unlicense"
] |
permissive
|
ApiO/Gonp
|
b8a39be4297cbe4248174b044d4586483c876add
|
98571f8b8eb8526416a6a8da880d8b0e11056cc2
|
refs/heads/master
| 2020-05-24T18:10:38.887082 | 2019-05-18T20:58:51 | 2019-05-18T20:58:51 | 187,403,549 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 773 |
cpp
|
#include <string>
#include <engine/pge.h>
#include <runtime/memory.h>
using namespace pge;
namespace app
{
void init();
void update(f64 delta_time);
void render();
void shutdown();
char data_path[_MAX_PATH];
}
inline void handle_args(int argc, char * argv[])
{
if (argc == 1){
strcpy(app::data_path, "../../../data");
return;
}
strcpy(app::data_path, argv[1]);
}
int main(int argc, char * argv[])
{
handle_args(argc, argv);
memory_globals::init();
Allocator *a = &memory_globals::default_allocator();
{
application::init(app::init, app::update, app::render, app::shutdown, app::data_path, *a);
while (!application::should_quit())
application::update();
application::shutdown();
}
memory_globals::shutdown();
}
|
[
"[email protected]"
] | |
ca1c86671a04731badaa6646586e3904ed526008
|
20c42cb2be000dc5b6f33a953e98e4d75c425d45
|
/small_project_code/argo_cli/core/argo_cli_mgr.cpp
|
5e5af099112ce6d596902257f62021c9341c73b1
|
[] |
no_license
|
lufb/code
|
ac5e9b056f54baf4f8fb3e955ac71b7c5339d39c
|
cf72556e77a45030e266dd1ea6e34b17219f3aba
|
refs/heads/master
| 2020-12-18T18:40:49.388650 | 2016-06-15T03:11:07 | 2016-06-15T03:11:07 | 28,075,225 | 0 | 0 | null | 2014-12-17T07:20:56 | 2014-12-16T07:14:11 |
C
|
GB18030
|
C++
| false | false | 27,958 |
cpp
|
#include <assert.h>
#include "argo_cli_mgr.h"
#include "argo_sock.h"
#include "argo_global.h"
#include "argo_error.h"
#include "argo_pro.h"
#include "argo_ckcrc16.h"
#include "argo_base.h"
#include "MFile.h"
#include "mask_decom.h"
#include "zlib_compress.h"
#ifdef LINUXCODE
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#endif
#define SELECT_TIME_OUT 1 // select ็่ถ
ๆถๆถ้ด
/** ่ฎพ็ฝฎไธไธชtimeval็ๆถ้ด*/
#define INIT_TIMEVAL(_timeval_, _timeout_) \
do{ \
_timeval_.tv_sec = _timeout_; \
_timeval_.tv_usec = 0; \
}while(0)
MDealPro::MDealPro()
{
}
MDealPro::~MDealPro()
{
}
void MDealPro::Init()
{
}
void MDealPro::FillArgoBae(argo_base *base)
{
Global_argo_base.heart_times = base->heart_times;
Global_argo_base.recon_times = base->recon_times;
if(Global_argo_base.recon_times == 0)
Global_argo_base.recon_times = 1;
}
int MDealPro::FilllArgoOption(argo_hello *option, unsigned int op_count)
{
unsigned int i;
sc_option *op;
for(i = 0; i < op_count; ++i){
argo_hello *cur_op = option + i;
op = (sc_option*)malloc(sizeof(sc_option));
if(op == NULL)
return BUILD_ERROR(E_OS, E_MALLOC);
memset(op, 0, sizeof(*op));
strncpy(op->sc_op.file_name, cur_op->file_name, sizeof(op->sc_op.file_name)-1);
dos2unix_path(op->sc_op.file_name, strlen(op->sc_op.file_name));
op->sc_op.file_type = cur_op->file_type;
op->sc_op.old_del = cur_op->old_del;
Global_Log.writeLog(LOG_TYPE_INFO, "ๆถๅฐๆๅกๅจๆไปถ้
็ฝฎไฟกๆฏ[file_name:%s][file_type:%d][old_del:%d]",
op->sc_op.file_name, cur_op->file_type, cur_op->old_del);
list_add_tail(&(op->list_node), &Global_sc_op_head);
}
return 0;
}
//ๅ ้คๆไปถ
bool MDealPro::TryDeleteFile( char *strFile, int iTryTimes)
{
int iTry = 0;
while( iTry < iTryTimes )
{
if( MFile::DeleteFile( strFile) < 0 )
{
Sleep(500);
iTry++;
}
return (true);
}
return (false);
}
// ๅๅปบๆๆไปถ็็ฎๅฝ็ปๆ
int MDealPro::TryCreateDirIfNeed( const char* filename)
{
char fileDir[MAX_PATH]={0};
char* pDst;
int errorcode;
pDst = strrchr(filename, '/');
strncpy(fileDir, filename, pDst - filename);
if( MFile::IsExist( fileDir) == true )
return 0;
if( ( errorcode = MFile::CreateDirectoryTree( MString( fileDir ) )) <0 )
{
Global_Log.writeLog( LOG_TYPE_ERROR, 0, "ๅๅปบ็ฎๅฝ[%s]ๅคฑ่ดฅ\n",fileDir );
return BUILD_ERROR(_OSerrno(), E_CRT_DIR);
}
return 0;
}
int MDealPro::_Write_File(char *file_name, unsigned int modify_time, unsigned char *file_buf, unsigned int buf_size)
{
int err;
MFile mf;
err = TryCreateDirIfNeed(file_name);
if(err)
return err;
if(!MFile::IsExist(file_name))
mf.Create(file_name);
err = mf.OpenWrite(file_name);
if(err != 1){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆๅผๆไปถ[%s]ๅบ้[%d]", file_name, err);
return BUILD_ERROR(_OSerrno(), E_OPEN_WRITE);
}
err = mf.Write((const char *)file_buf, buf_size);
if(err != buf_size){
mf.Close();
MFile::DeleteFile(file_name);
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅๆไปถ[%s]ๅบ้[%d]", file_name, err);
return BUILD_ERROR(_OSerrno(), E_WRITE_WRITE);
}
mf.SetFileLength(buf_size);
// ๆดๆนๆไปถๆถ้ด
if( ( err = mf.SetUpdateDateTime( MDateTime(modify_time) )) <0 )
{
mf.Close();
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆดๆฐๆไปถ[%s]ๆถ้ดๅบ้[%d]", file_name, err);
return BUILD_ERROR(_OSerrno(), E_FILE_TIME);
}
return 0;
}
int MDealPro::Write_File(char *file_name, unsigned int modify_time, unsigned char *file_buf, unsigned int buf_size)
{
int err;
char abs_file_name[FILE_NAME_SIZE];
sprintf(abs_file_name, "%s/%s", Global_Loc_Option.GetMain(), file_name);
err = TryCreateDirIfNeed(abs_file_name);
if(err)
return err;
if(!MFile::IsExist(abs_file_name)){
char abs_file_name_tmp[FILE_NAME_SIZE];
sprintf(abs_file_name_tmp, "%s~~TMP~~", abs_file_name);
err = _Write_File(abs_file_name_tmp, modify_time, file_buf, buf_size);
if(err){
MFile::DeleteFile(abs_file_name_tmp);
return err;
}
//ๆนๅ
err = MFile::RenameFileName(abs_file_name_tmp, abs_file_name);
if(err != 1){
MFile::DeleteFile(abs_file_name_tmp);
Global_Log.writeLog(LOG_TYPE_ERROR, "้ๅฝๅๆไปถ[%s]->[%s]ๅคฑ่ดฅ",
abs_file_name_tmp, abs_file_name);
return BUILD_ERROR(_OSerrno(), E_RENAME_FILE);
}
return 0;
}else{
return _Write_File(abs_file_name, modify_time, file_buf, buf_size);
}
}
int MDealPro::DealCpData_MKTD(argo_all_head *head, unsigned char *file_buf, unsigned int buf_size)
{
int err;
local_file_node *pNode = Global_Loc_File.Find(head->file_name, FILE_TYPE_MKTD);
err = CpCheck(head, file_buf, buf_size);
if(err)
return err;
// ๅๅฐ็ฃ็ไธ
err = Write_File(head->file_name, head->modify_time, file_buf, buf_size);
if(err)
return err;
if(pNode == NULL){ //ๆฐๅปบ้พ่กจ
return Global_Loc_File.Add2(head, file_buf);
}else{ //ๆดๆฐๆฐๆฎ
return Global_Loc_File.UpNode(head, file_buf, buf_size, pNode );
}
}
int MDealPro::DealCpData_FJY(argo_all_head *head, unsigned char *file_buf, unsigned int buf_size)
{
int err;
err = CpCheck(head, file_buf, buf_size);
if(err)
return err;
return Write_File(head->file_name, head->modify_time, file_buf, buf_size);
}
int MDealPro::CpCheck(argo_all_head *head, unsigned char *buf, unsigned int buf_size)
{
unsigned char tmp_hash[HASH_SIZE];
if(head->file_size != buf_size){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]ๅ
จ้ๅ
ๆถ๏ผๅ่ฎฎๅคดๅธฆ็ๆฐๆฎๅคงๅฐ[%u]ไธๆไปถๅคงๅฐ[%u]ไธไธ่ด",
head->file_name, head->file_size, buf_size);
return BUILD_ERROR(0, E_FILE_SIZE);
}
get_hash(tmp_hash, buf, buf_size);
if(memcmp(head->hash_new, tmp_hash, HASH_SIZE)){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]ๅ
จ้ๅ
ๆถ๏ผๅ่ฎฎๅคดๅธฆ็hash[%-20.20s]ไธๆไปถhash[%-20.20s]ไธไธ่ด",
head->file_name, head->hash_new, tmp_hash);
return BUILD_ERROR(0, E_FILE_SIZE);
}
return 0;
}
int MDealPro::DealCpData(unsigned char *buf, unsigned int buf_size)
{
int err;
argo_all_head *cp = (argo_all_head*)(buf+sizeof(argo_head));
if(buf_size < sizeof(argo_head) + sizeof(argo_all_head))
return BUILD_ERROR(0, E_MINHEAD_SIZE);
dos2unix_path(cp->file_name, my_min(strlen(cp->file_name), FILE_NAME_SIZE));
switch(cp->file_type)
{
case FILE_TYPE_MKTD:
err = DealCpData_MKTD(cp,
buf+sizeof(argo_head) + sizeof(argo_all_head),
buf_size - sizeof(argo_head) - sizeof(argo_all_head));
if(err != 0)
return err;
break;
case FILE_FJY:
err = DealCpData_FJY(cp,
buf+sizeof(argo_head) + sizeof(argo_all_head),
buf_size - sizeof(argo_head) - sizeof(argo_all_head));
if(err != 0)
return err;
break;
default:
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]็ๅ
จ้ๅ
็ฑปๅไธๆญฃ็กฎ[%d]", cp->file_name, cp->file_type);
return BUILD_ERROR(0, E_UN_FILETYPE);
}
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๆถๅฐๆไปถ[%s]็ๅ
จ้ๅ
[%u]", cp->file_name, buf_size - sizeof(argo_head) - sizeof(argo_all_head));
#endif
return 0;
}
int MDealPro::ChkMemIsZero(unsigned char *buf, unsigned int size)
{
unsigned int i;
for(i = 0; i < size; ++i){
if(buf[i])
return BUILD_ERROR(0, E_MASK_NO_ZERO);
}
return 0;
}
int MDealPro::UpMemory(local_file_node *pNode,
unsigned char *buf)
{
argo_mask *p_mask = (argo_mask*)buf;
unsigned char *p_mask_data = buf+sizeof(argo_mask);
argo_dic_dc *p_dc = NULL;
unsigned int mask_size = 0;
unsigned int i;
int err;
unsigned int change_size;
for(i = 0; i < LEVELS; ++i){
mask_size += p_mask->size[i];
}
p_dc = (argo_dic_dc *)(buf+sizeof(argo_mask)+mask_size);
p_dc->swap(); // note: ็ฟป่ฝฌ
change_size = *((unsigned int *)(buf+sizeof(argo_mask)+mask_size+sizeof(argo_dic_dc)));
err = mask_decom(p_dc, pNode, p_mask, p_mask_data, buf+sizeof(argo_mask)+mask_size+sizeof(unsigned int)+sizeof(argo_dic_dc), change_size);
if(err)
return err;
return ChkMemIsZero(p_mask_data, mask_size);
}
int MDealPro::DealUpData(unsigned char *buf, unsigned int buf_size)
{
int err;
argo_up_head *head;
local_file_node *pNode;
unsigned char tmp_hash[HASH_SIZE];
if(buf_size < sizeof(argo_head) + sizeof(argo_up_head))
return BUILD_ERROR(0, E_MINHEAD_SIZE);
head = (argo_up_head*)(buf+sizeof(argo_head));
dos2unix_path(head->file_name, my_min(FILE_NAME_SIZE, strlen(head->file_name)));
pNode = Global_Loc_File.Find(head->file_name, FILE_TYPE_MKTD);
if(head->file_type != FILE_TYPE_MKTD){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไธๆฏๆๆไปถๅ[%s]็ฑปๅ[%d]็ๅข้ๆดๆฐ", head->file_name, head->file_type);
return BUILD_ERROR(0, E_UN_FILETYPE);
}
if(pNode == NULL){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅจๅ
ๅญไธญๆฒกๆพๅฐๆไปถๅ[%s]็ฑปๅ็็ธๅ
ณไฟกๆฏ", head->file_name);
return BUILD_ERROR(0, E_ABORT1);
}
if(pNode->file_size != head->file_size){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]ๅ
ๅญไธญ็ๅคงๅฐ[%u]ไธๆถๅฐ็ๅคงๅฐ[%u]ไธ็ญ๏ผไธ่ฝ่ฟ่กๅข้ๆดๆฐ",
head->file_name, pNode->file_size, head->file_size);
return BUILD_ERROR(0, E_ABORT1);
}
if(memcmp(pNode->file_cur_hash, head->hash_old, HASH_SIZE)){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]ๅ
ๅญไธญ็hash[%-20.20s]ๅ่ฎฎไธญ็่hash[%-20.20s]ไธ็ญ๏ผไธ่ฝ่ฟ่กๅข้ๆดๆฐ",
head->file_name, pNode->file_cur_hash, head->hash_old);
return BUILD_ERROR(0, E_ABORT1);
}
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๆถๅฐๆไปถ[%s]็ๅข้ๅ
ๅคงๅฐ[%d]", pNode->file_name, buf_size-sizeof(argo_head)-sizeof(argo_up_head)-sizeof(argo_dic_dc));
#endif
err = UpMemory(pNode, buf+sizeof(argo_head)+sizeof(argo_up_head));
if(err)
return err;
get_hash(tmp_hash, pNode->file_buf, pNode->file_size);
if(memcmp(tmp_hash, head->hash_new, HASH_SIZE)){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถ[%s]ๅ
ๅญไธญๆดๆฐๅhash[%-20.20s]ๅ่ฎฎไธญ็ๆๅกๅจๅธฆ็hash[%-20.20s]ไธ็ญ๏ผๅข้ๆดๆฐๅคฑ่ดฅ",
head->file_name, tmp_hash, pNode->file_cur_hash);
return BUILD_ERROR(0, E_UP_HASH);
}
err = Write_File(head->file_name, head->modify_time, pNode->file_buf, pNode->file_size);
if(err)
return err;
memmove(pNode->file_cur_hash, head->hash_new, HASH_SIZE);
pNode->file_time = head->modify_time;
return 0;
}
int MDealPro::FilllOption(unsigned char *buf, unsigned int buf_size)
{
int err;
int count;
if(buf_size < sizeof(argo_head) + sizeof(argo_base))
return BUILD_ERROR(0, E_MINHEAD_SIZE);
argo_base *base_info= (argo_base*)(buf+sizeof(argo_head));
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_INFO, "ๆถๅฐ็ๆๅกๅจๅบๆฌ้
็ฝฎไฟกๆฏ[heart_times:%u][recon_times:%u]",
base_info->heart_times, base_info->recon_times);
#endif
FillArgoBae(base_info);
assert(buf_size >= sizeof(argo_head) + sizeof(argo_base));
assert((buf_size - sizeof(argo_head) - sizeof(argo_base))%sizeof(argo_hello) == 0);
argo_hello *hello = (argo_hello*)(buf+sizeof(argo_head) + sizeof(argo_base));
count = (buf_size - sizeof(argo_head) + sizeof(argo_base))/sizeof(argo_hello);
if(count == 0)
return BUILD_ERROR(0, E_OPTION_00);
if((err = FilllArgoOption(hello, count)) != 0)
return err;
return 0;
}
int MDealPro::CheckSoftVer(argo_head *p_head)
{
if(p_head->main != Global_Main_Ver){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆๅกๅจไธป็ๆฌๅท[%u]ไธๅฎขๆท็ซฏไธป็ๆฌๅท[%u]ไธ็ญ๏ผไธๅ
ผๅฎน๏ผ็จๅบ้ๅบ", p_head->main, Global_Main_Ver);
exit(0);
}
return 0;
}
int MDealPro::DealProFunc(unsigned char *buf, unsigned int buf_size)
{
int err;
if(buf_size < sizeof(argo_head))
return BUILD_ERROR(0, E_MINHEAD_SIZE);
argo_head *p_head = (argo_head*)buf;
switch(p_head->pro)
{
case PRO_CS_00: // ๅฎขๆท็ซฏๅฐๆๅกๅจ็ๅฟ่ทณๅ
case PRO_CS_01: // ๅฎขๆท็ซฏๅฐๆๅกๅจ็ๆไปถไฟกๆฏๅ
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅฎขๆท็ซฏๆถๅฐๅๆๅกๅจๅ้็ๅ่ฎฎๅท[%u]", p_head->pro);
return BUILD_ERROR(0, E_PRO_DIR);
case PRO_SC_O0: // ๆๅกๅจๅฐๅฎขๆท็ซฏ็ๅฟ่ทณๅ
// ๅฟ่ทณๅ
็ดๆฅ่ทณ่ฟ
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๆถๅฐๆๅกๅจไธๅ็ๅฟ่ทณๅ
");
#endif
break;
case PRO_SC_OP: // ๆๅกๅจๅฐๅฎขๆท็ซฏ็้
็ฝฎๅ
CheckSoftVer(p_head);//ๆ ก้ช็จๅบ็ๅ
ผๅฎนๆง
err = FilllOption(buf, buf_size);
if(err)
return 0;
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๆถๆๅกๅจๆๆ้
็ฝฎไฟกๆฏๅฎๆ");
err = Glboal_Mgr.upload_local();
if(err)
return err;
Global_Log.writeLog(LOG_TYPE_INFO, "ไธไผ ๅ
จ้จๆฌๅฐๆไปถhashๆๅ");
break;
case PRO_SC_AD: // ๆๅกๅจๅฐๅฎขๆท็ซฏ็ๅข้ๅ
err = DealUpData(buf, buf_size);
if(err)
return err;
break;
case PRO_SC_AL: // ๆๅกๅจๅฐๅฎขๆท็ซฏ็ๅ
จ้ๅ
err = DealCpData(buf, buf_size);
if(err)
return err;
break;
default:
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆถๅฐๆช็ฅๅ่ฎฎๅท[%u]", p_head->pro);
return BUILD_ERROR(0, E_UN_PROTYPE);
}
// ๆๅ่ฟๅ0
return 0;
}
//////////////////////////////////////////////////////////////////////////
MDealBDE::MDealBDE()
{
had_chk_bde = false;
Init();
}
MDealBDE::~MDealBDE()
{
}
void MDealBDE::Init()
{
status = BDE_00;
p_head = NULL;
once_bde_size = 0;
Global_Pro_Ctx.pro_buf_used = 0;
deal_pro.Init();
}
int MDealBDE::ChkCrc()
{
bde_head *head = (bde_head*)once_bde_buf;
unsigned short crc = argo_ckcrc16_calc(once_bde_buf+2, once_bde_size-2);
if(crc != head->crc){
Global_Log.writeLog(LOG_TYPE_ERROR, "CRC ๆถๅฐ็[%u]!=่งฃๅบๆฅ็[%u]", head->crc, crc);
return BUILD_ERROR(0, E_CRC);
}
return 0;
}
int MDealBDE::ChkBDE()
{
BDE_STATUS rcv_sta = (BDE_STATUS)(p_head->bde_type);//ๆถๅฐๅ
็็ฑปๅ
switch(rcv_sta)
{
case BDE_00:
assert(0);
return BUILD_ERROR(0, E_UNBDETYPE2);
case BDE_E:
if(status != BDE_D && status != BDE_BD){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
Global_Com_Ctx.Set1();
break;
case BDE_D:
if(status != BDE_B && status != BDE_BD && status != BDE_D){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
break;
case BDE_DE:
if(status != BDE_D && status != BDE_BD){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
Global_Com_Ctx.Set1();
break;
case BDE_B:
if(status != BDE_00){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
Global_Com_Ctx.Set0();
break;
case BDE_BE:
return BUILD_ERROR(0, E_UNBDETYPE1);
case BDE_BD:
if(status != BDE_00){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
Global_Com_Ctx.Set0();
break;
case BDE_BDE:
if(status != BDE_00 && status != BDE_BDE){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDE็ถๆ็ฑ[%u]->[%u]ๆ้ฎ้ข",status, rcv_sta);
return BUILD_ERROR(0, E_UNBDETYPE1);
}
Global_Com_Ctx.Set0();
Global_Com_Ctx.Set1();
break;
default:
assert(0);
return BUILD_ERROR(0, E_UNBDETYPE);
}
// ๆญฃๅธธ็ถๆไธ็ถๆๅ่ฟ
status = rcv_sta;
return 0;
}
void MDealBDE::ChkBdeVer(bde_head *head)
{
if(head->main != Global_BDE_Main){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆๅกๅจBDEไธป็ๆฌๅท[%u]ไธ็ญไบๅฎขๆท็ซฏ็BDEไธป็ๆฌๅท[%d],็จๅบ้ๅบ",
head->main != Global_BDE_Main);
exit(0);
}
had_chk_bde = true;
}
int MDealBDE::RcvOnceBDE(int sock)
{
int err;
// SETP1: ๆถBEDๅคด
err = MSocket::rcvDataNonBlock(sock, (char *)once_bde_buf, sizeof(bde_head));
if(err != 0)
return err;
if(!had_chk_bde){
ChkBdeVer((bde_head*)once_bde_buf);
}
p_head = (bde_head *)once_bde_buf;
if(sizeof(bde_head) + p_head->size > MAX_BDE_SIZE){
Global_Log.writeLog(LOG_TYPE_ERROR, "BDEๅคงๅฐ่ถ็[ๆๅคงๅผ:%u][BDEๅคด:%u][BDEไฝ:%u]",
MAX_BDE_SIZE, sizeof(bde_head), p_head->size);
return BUILD_ERROR(0, E_MAX_BDE_SIZE);
}
// SETP2: ๆถBEDไฝ
err = MSocket::rcvDataNonBlock(sock, (char *)(once_bde_buf+sizeof(bde_head)), p_head->size);
if(err != 0)
return err;
once_bde_size = sizeof(bde_head) + p_head->size;
return 0;
}
int MDealBDE::HadRcvedOnceBDE()
{
if( status == BDE_E ||
status == BDE_DE||
status == BDE_BDE){
return 1;
}
return 0;
}
int MDealBDE::ZlibDecomCp(unsigned char *in_buf, unsigned int in_size)
{
int err;
err = Global_Com_Ctx.Com_Data(in_buf, in_size);
if(err){
Global_Log.writeLog(LOG_TYPE_ERROR, "่งฃๅๆฐๆฎๅบ้[%d]", err);
return BUILD_ERROR(0, E_UNCOMPRESS);
}
return 0;
}
int MDealBDE::UnComCp(unsigned char *in_buf, unsigned int in_size)
{
int err;
// ไฟ่ฏ่ณๅฐๆCHUNK็ฉบ้ฒ็ฉบ้ด
err = try_realloc_pro_buf();
if(err)
return err;
memmove(Global_Pro_Ctx.pro_buf + Global_Pro_Ctx.pro_buf_used, in_buf, in_size);
Global_Pro_Ctx.pro_buf_used += in_size;
return 0;
}
// ๅฐๅไธชBDEๅ
ๆฐๆฎๆทๅฐๅ่ฎฎ็ผๅฒๅบ
int MDealBDE::CpToProBuf()
{
assert(Global_Pro_Ctx.pro_buf_size % CHUNK == 0);
assert(Global_Pro_Ctx.pro_buf_size >= Global_Pro_Ctx.pro_buf_used);
assert(p_head != NULL);
switch(p_head->com_type)
{
case 0x00: // ไธๅ็ผฉ
return UnComCp(once_bde_buf+sizeof(bde_head), once_bde_size-sizeof(bde_head));
case 0x01: // zlibๅ็ผฉ
return ZlibDecomCp(once_bde_buf+sizeof(bde_head), once_bde_size-sizeof(bde_head));
default:
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆถๅฐๆช็ฅ็ฑปๅ็ๅ็ผฉ็ฑปๅ[%d]", p_head->com_type);
return BUILD_ERROR(0, E_UN_COMTYPE);
}
}
int MDealBDE::DealOnceBDE(int sock)
{
int err;
// STEP1: ๆถๅฎๆดไธไธชBDEๅ
err = RcvOnceBDE(sock);
if(err != 0)
goto END;
// STEP2: ๆ ก้ชๅ
ๆฏๅฆๆญฃ็กฎ
err = ChkCrc();
if(err != 0)
goto END;
Global_Com_Ctx.ResetSta();
// STEP3: ๆ ก้ชBDE็ถๆ
err = ChkBDE();
if(err != 0)
goto END;
// TODO
if(Global_Com_Ctx.Get0() != 0){
if((err = Global_Com_Ctx.Com_Init()) != 0)
return err;
}
// STEP4: ๅฐๆฐๆฎๆพๅฐๅ่ฎฎๆฐๆฎไธญ
err = CpToProBuf();
if(err != 0)
goto END;
// STEP5: ๆถๅฎไธไธชๅ่ฎฎๅๅปๆฐๆฎๅค็
if(HadRcvedOnceBDE()){
err = deal_pro.DealProFunc(Global_Pro_Ctx.pro_buf, Global_Pro_Ctx.pro_buf_used);
Init(); // ้ๆฐๅๅงๅ๏ผไปฅไพฟไธๆฌกBDEๆถๅ
if(err != 0)
goto END;
}
END:
if(Global_Com_Ctx.Get1()){
Global_Com_Ctx.Com_Destroy();
}
return err;
}
//////////////////////////////////////////////////////////////////////////
MArgoCliMgr::MArgoCliMgr()
{
sock = -1;
rcv_t = time(NULL);
snd_t = time(NULL);
}
MArgoCliMgr::~MArgoCliMgr()
{
}
void MArgoCliMgr::Init()
{
deal_bde.Init();
}
// ้่ฟๆถ็่ตๆบ้ๆพ
void MArgoCliMgr::ReInit()
{
// ้ๆพ็ฑGlobal_sc_op_headๆๅ็ๆๅกๅจไธๅ็้
็ฝฎไฟกๆฏ
do{
struct list_head *pList, *pSafe;
sc_option *pNode;
list_for_each_safe(pList, pSafe, &Global_sc_op_head){
pNode = list_entry(pList, sc_option, list_node);
assert(pNode != NULL);
list_del(pList);
free(pNode);
}
}while(0);
// ้ๆพ็ฑGlobal_Loc_Fileๆๅ็;
Global_Loc_File.Destroy();
Global_Pro_Ctx.pro_buf_used = 0;
Global_Com_Ctx.Com_Destroy();
Glboal_Mgr.Init();
}
void MArgoCliMgr::set_select_timeout(int time_out)
{
INIT_TIMEVAL(tv, time_out);
}
#ifndef LINUXCODE
void FileTimeToTime_t( FILETIME ft, time_t *t )
{
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
*t = ((LONGLONG)(ui.QuadPart - 116444736000000000) / 10000000);
}
#endif
// ๅฐไธไธชtime_t็ฑปๅ็ๆถ้ด่ฝฌๆขไธบ่ท็ฆป1970ๅนด็ๅคฉๆฐ
unsigned int GetDayOfTime(time_t t)
{
unsigned int one_day_secs = 24*60*60;
return t/one_day_secs;
}
int MArgoCliMgr::build_local_mktd(sc_option *pNode)
{
char tmp_file[FILE_NAME_SIZE*2+1];
memset(tmp_file, 0, sizeof(tmp_file));
sprintf(tmp_file, "%s/%s", Global_Loc_Option.GetMain(), pNode->sc_op.file_name);
if(MFile::IsExist(tmp_file))
return Global_Loc_File.Add(pNode, tmp_file, NULL);
return 0;
}
int MArgoCliMgr::is_corect_time(unsigned int t, unsigned int old_del)
{
int tmp_old_del;
tmp_old_del = GetDayOfTime(time(NULL)) - GetDayOfTime(t);
printf("[%d]", tmp_old_del);
if(tmp_old_del < 0)
return 1;
if((unsigned int)tmp_old_del <= old_del)
return 1;
return 0;
}
int MArgoCliMgr::build_local_fjy(sc_option *pNode)
{
#ifndef LINUXCODE
WIN32_FIND_DATA stFileInfo;
time_t lastModifyTime;
char abs_name[1024];
char dir_name[1024];//nodeไธญ็ๅญ็ฎๅฝ็ปๆ
char fjy_name[1024];
int err = 0 ;
char *last_sep;
last_sep = strrchr(pNode->sc_op.file_name, '/');
if(last_sep){ // ๆๅญ็ฎๅฝ
memmove(dir_name, pNode->sc_op.file_name, last_sep-pNode->sc_op.file_name);
dir_name[last_sep-pNode->sc_op.file_name] = 0;
}else{ // ๆฒกๆๅญ็ฎๅฝ
dir_name[0] = 0;
}
sprintf(abs_name, "%s/%s", Global_Loc_Option.GetMain(), pNode->sc_op.file_name, sizeof(abs_name)-1);
memset(&stFileInfo, 0, sizeof(stFileInfo));
HANDLE pFile = ::FindFirstFile(abs_name, &stFileInfo);
if(pFile == INVALID_HANDLE_VALUE)
{
Global_Log.writeLog(LOG_TYPE_INFO, "็ฎๅฝ[%s]ๆๆถไธๅญๅจ", abs_name);
return 0;
}
do
{
if(stFileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
continue;
}
else
{
if(dir_name[0] == 0){
strncpy(fjy_name, stFileInfo.cFileName, sizeof(fjy_name)-1);
sprintf(abs_name, "%s/%s", Global_Loc_Option.GetMain(), stFileInfo.cFileName);
}else{
sprintf(fjy_name, "%s/%s", dir_name, stFileInfo.cFileName);
sprintf(abs_name, "%s/%s/%s", Global_Loc_Option.GetMain(), dir_name, stFileInfo.cFileName);
}
::FileTimeToTime_t(stFileInfo.ftLastWriteTime, &lastModifyTime);
if(!is_corect_time(lastModifyTime, pNode->sc_op.old_del)){
//MFile::DeleteFile(abs_name); //่ฎฐๅพๆๅผ
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๅ ้คๆไปถ[%s]", abs_name);
#endif
continue;
}
//ๆถ้ดไธๅน้
็ฌฆ้ฝๆปก่ถณ๏ผๅ ๅฐ้พ่กจไธญ
err = Global_Loc_File.Add(pNode, abs_name, fjy_name);
if(err)
break;
}
}while(::FindNextFile(pFile, &stFileInfo));
::FindClose(pFile);
return err;
#else
//linuxไปฃ็
struct dirent *dirp;
DIR *dir;
struct stat statbuf;
char path[1024];
sprintf(path, "%s/%s",
Global_Loc_Option.GetMain(),
MFile::GetPathFromString(pNode->sc_op.file_name).c_str());
//ๆๅผ็ฎๅฝ
if((dir = opendir(path)) == NULL){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆๅผ็ฎๅฝ[%s]่ฏปๅบ้", path);
return BUILD_ERROR(_OSerrno(), E_FISTFILE);
}
//้ๅ็ฎๅฝ
while((dirp = readdir(dir)) != NULL){
if(strcmp(dirp->d_name, ".") == 0 ||
strcmp(dirp->d_name, "..") == 0){
continue;//ๅฟฝ็ฅ
}
sprintf(path, "%s/%s", pDir, dirp->d_name);
lstat(path, &statbuf);
if(S_ISDIR(statbuf.st_mode)){
scanfdir(path, ucDepth, regu, scanTime, dirHeadSize);
}else{//ๆไปถ
if(inner_match(dirp->d_name, regu)){
AddToArray(path+dirHeadSize, statbuf.st_mtime, statbuf.st_size);
}
}
}
closedir(dir);
return 0;
#endif
}
int MArgoCliMgr::build_local()
{
struct list_head *pTmp;
sc_option *pNode;
int err;
list_for_each(pTmp, &Global_sc_op_head)
{
pNode = list_entry(pTmp, sc_option, list_node);
assert(pNode != NULL);
switch(pNode->sc_op.file_type)
{
case FILE_TYPE_MKTD:
err = build_local_mktd(pNode);
if(err)
return err;
break;
case FILE_FJY:
err = build_local_fjy(pNode);
if(err)
return err;
break;
default:
Global_Log.writeLog(LOG_TYPE_ERROR, "ๆไปถๅ[%s]ไธ็ฅ้็ๆไปถ็ฑปๅ[%u]", pNode->sc_op.file_name, pNode->sc_op.file_type);
return BUILD_ERROR(0, E_UN_FILETYPE);
}
}
return 0;
}
int MArgoCliMgr::up_local()
{
return Global_Loc_File.UpInfo(sock);
}
int MArgoCliMgr::upload_local()
{
int err;
err = build_local();
if(err)
return err;
err = up_local();
if(err)
return err;
return 0;
}
time_t MArgoCliMgr::get_cur_time()
{
return time(NULL);
}
int MArgoCliMgr::trySendHeart()
{
int err;
if(get_cur_time() - snd_t > Global_argo_base.heart_times){
snd_t = time(NULL);
err = Global_Loc_File.SendHeart(sock);
if(err){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅๅฟ่ทณๅ
ๅ็้่ฏฏ[%d]", err);
return err;
}
#ifdef _DEBUG
Global_Log.writeLog(LOG_TYPE_DEBUG, "ๅไธๅ้ๅฟ่ทณๅ
");
#endif
}
return 0;
}
int MArgoCliMgr::is_stoped()
{
return m_Thread.GetThreadStopFlag() == true ? 1 : 0;
}
void MArgoCliMgr::close_sock()
{
if(sock != -1)
MSocket::close_sock(sock);
sock = -1;
}
int MArgoCliMgr::main_func(char *ip, unsigned short port)
{
fd_set fdRead; /* ๅฏ่ฏปๅฅๆฅๅญ้ๅ*/
int err;
char ip_num[256];
/* dns่ฝฌๆข */
err = MSocket::dnsToIP(ip, port, ip_num, sizeof(ip_num)-1);
if( err != 0 ){
Global_Log.writeLog(LOG_TYPE_DEBUG,
"ๅฏน[%s]่ฟ่กDNSๅบ้[%d]",
ip, err);
goto END;
}
/* STEP1: ่ฟๆฅ */
if((sock = MSocket::block_connect(ip_num, port)) < 0){
sock = BUILD_ERROR(_OSerrno(), E_CONNECT);
Global_Log.writeLog(LOG_TYPE_ERROR, "่ฟๆฅ[%s][%d]ๅ็้่ฏฏ[%d]", ip, port, sock);
goto END;
}
Global_Log.writeLog(LOG_TYPE_INFO, "่ฟๆฅๆๅกๅจ[%s:%d]ๆๅ", ip, port);
snd_t = time(NULL);
while ( m_Thread.GetThreadStopFlag( ) == false ){
// ๅฐ่ฏๅๅฟ่ทณๅ
err = trySendHeart();
if(err)
goto END;
set_select_timeout(SELECT_TIME_OUT); //่ฎพ็ฝฎselect่ถ
ๆถๆถ้ด
FD_ZERO(&fdRead);
FD_SET(sock, &fdRead);
err = select(0, &fdRead, NULL, NULL, &tv);
if(err > 0) /* ๆๅฅๆฅๅญๅฏ่ฏป */
{
rcv_t = time(NULL);
err = deal_bde.DealOnceBDE(sock);
if(err != 0){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅค็ๆๅกๅจๆถๅฐ็ๆฐๆฎๅ็้่ฏฏ[%d]", err);
goto END;
}
}else if(err < 0)
{
assert(0);
err = BUILD_ERROR(_OSerrno(), E_ABORT1);
Global_Log.writeLog(LOG_TYPE_ERROR, "selectๅบ้[%d]\n", err);
goto END;
}
else{
if(get_cur_time() - rcv_t > Global_argo_base.heart_times * 2){
Global_Log.writeLog(LOG_TYPE_ERROR, "ๅฎขๆท็ซฏๅทฒ็ป[%d]ๆฒกๆๆถๅฐๆๅกๅจๅๆฅ็ๆฐๆฎ๏ผ่ฎคไธบๅทฒๆฏๆญป้พ่ทฏ๏ผๆญๅผ้พๆฅ",
get_cur_time() - rcv_t);
err = BUILD_ERROR(0, E_TIMEOUT_HEART);
goto END;
}
}
}
END:
close_sock();
Global_Log.writeLog(LOG_TYPE_ERROR, "ไธปๆง้ๅบ็้่ฏฏ็ [%u][%u],ๆญๅผๆๅกๅจ[%s][%d]",
GET_SYS_ERR(err), GET_USER_ERR(err), ip, port);
return 0;
}
void * __stdcall MArgoCliMgr::ArgoThreadFun( void * pIn )
{
MArgoCliMgr *classptr = (MArgoCliMgr * )pIn;
while(classptr->m_Thread.GetThreadStopFlag() == false)
{
classptr->main_func(Global_Loc_Option.GetIP(), Global_Loc_Option.GetPort());
classptr->ReInit();
MThread::Sleep(Global_argo_base.recon_times * 1000);
}
return 0;
}
/* ่ฟๅๅผ๏ผ
0๏ผ ๆๅ
*/
int MArgoCliMgr::start_mainthread()
{
int err;
if( ( err = m_Thread.StartThread("ๅทฅไฝไธป็บฟ็จ", ArgoThreadFun,this ) ) != 1 )
{
Global_Log.writeLog( LOG_TYPE_ERROR, 0, "ๅๅปบargoๅทฅไฝ็บฟ็จๅคฑ่ดฅ[%s]",MErrorCode::GetErrString( err ).c_str() );
return BUILD_ERROR(_OSerrno(), E_CR_THREAD);
}
return 0;
}
MCom_Ctx::MCom_Ctx()
{
had_init = false;
sta[0] = false;
sta[1] = false;
}
MCom_Ctx::~MCom_Ctx()
{
}
int MCom_Ctx::Com_Data(unsigned char *buf, unsigned int size)
{
return de_compress.Decompress(buf, size);
}
int MCom_Ctx::Com_Init()
{
int err;
if(!had_init){
if((err = de_compress.Init()) != 0){
return BUILD_ERROR(0, E_ABORT1);
}
had_init = true;
}else{
return BUILD_ERROR(0, E_ABORT1);
}
return 0;
}
void MCom_Ctx::Com_Destroy()
{
if(had_init)
de_compress.Destroy();
had_init = false;
ResetSta();
}
void MCom_Ctx::Set0()
{
sta[0] = true;
}
void MCom_Ctx::Set1()
{
sta[1] = true;
}
bool MCom_Ctx::Get0()
{
return sta[0];
}
bool MCom_Ctx::Get1()
{
return sta[1];
}
void MCom_Ctx::ResetSta()
{
sta[0] = false;
sta[1] = false;
}
|
[
"[email protected]"
] | |
b60977a36dff134d41efbce8a3d3801e4e4729c9
|
eb70bd22125578284fd731b95101194428d39a05
|
/Classes/Server/NodeJSServer.cpp
|
efbd6ee444291ba032fe154940d0c58f1174be74
|
[] |
no_license
|
vienbk91/BreakoutMulti
|
47a7d853f34c4038624f6535d53351c46c7bc587
|
003f7c796fe6d3ce4bad659a44292388a2fa8bcc
|
refs/heads/master
| 2020-05-02T21:41:22.611273 | 2015-12-27T05:24:20 | 2015-12-27T05:24:20 | 39,057,480 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,709 |
cpp
|
/*
* NodeJSServer.cpp
*
* Created on: 13 Jul 2015
* Author: chu
*/
#include "NodeJSServer.h"
NodeServer* NodeServer::_nodeServer = nullptr;
NodeServer* NodeServer::getInstance()
{
if(!_nodeServer){
_nodeServer = new (std::nothrow) NodeServer();
_nodeServer->init();
}
return _nodeServer;
}
void NodeServer::destroyInstance(){
if(_nodeServer->getClient() != nullptr){
_nodeServer->getClient()->disconnect();
}
_nodeServer = nullptr;
}
SIOClient* NodeServer::getClient(){
if(_socketClient != nullptr){
return _socketClient;
}
return nullptr;
}
bool NodeServer::init()
{
//============================================
// Connect server
std::string url = "ws://127.0.0.1:8080/";
_socketClient = SocketIO::connect(url , *this);
CCASSERT(_socketClient , "==============>Error! Can not create socketIO");
log("============> Connect to nodejs server : %s" , url.c_str() );
return true;
}
void NodeServer::startConnectWithHandle(std::string name, SIOEvent event)
{
_name = name;
if (_socketClient){
_socketClient->on(name.c_str() , event);
return;
}
log("Start Connect Failed");
}
void NodeServer::sendMessageWithName(string name, string message){
if (_socketClient){
_socketClient->emit(name.c_str(), message.c_str());
}
else{
log("Send Message Failed");
}
}
void NodeServer::onConnect(SIOClient* client){
log("================================> onConnect");
}
void NodeServer::onMessage(SIOClient* client, const string& data){
}
void NodeServer::onClose(SIOClient* client){
log("===============================> onClose");
}
void NodeServer::onError(SIOClient* client, const string& data){
log("===============================> onError");
}
|
[
"[email protected]"
] | |
db590cc94cb374d0ca542878794c0c4f4052eb71
|
f2339e85157027dada17fadd67c163ecb8627909
|
/Common/ConnectorWithProcess.h
|
9a81c606577737b40e145680d532f8793c004e71
|
[] |
no_license
|
fynbntl/Titan
|
7ed8869377676b4c5b96df953570d9b4c4b9b102
|
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
|
refs/heads/master
| 2021-09-01T22:52:37.516407 | 2017-12-29T01:59:29 | 2017-12-29T01:59:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,802 |
h
|
๏ปฟ/*******************************************************************
** ๆไปถๅ: ConnectorWithProcess.h
** ็ ๆ: (C) ๆทฑๅณๅฐๅท็ฝ็ป่กไปฝๆ้ๅ
ฌๅธ
** ๅๅปบไบบ: baoliang.shen
** ๆฅ ๆ: 2017/11/21
** ็ ๆฌ: 1.0
** ๆ ่ฟฐ: ๅ ๅ
ฅไบๆถๆฏๅๅๅค็ๅ่ฝ
** ๅบ ็จ: ไธปๅจ่ฟๆฅๅจๅบ็ฑปไบ
**************************** ไฟฎๆน่ฎฐๅฝ ******************************
** ไฟฎๆนไบบ:
** ๆฅ ๆ:
** ๆ ่ฟฐ:
********************************************************************/
#pragma once
#include "Connector.h"
#include "Processer.h"
#include "ByteRecord.h"
template<class TConn>
class ConnectorWithProcess : public Connector
{
public:
ConnectorWithProcess(Processer<TConn>& processer, ByteRecord& br, TimerAxis& timerAxis) :
Connector(timerAxis)
, m_Processer(processer)
, m_br(br)
{}
virtual ~ConnectorWithProcess() {}
virtual void OnRecv( IConnection * conn,LPVOID pData,DWORD dwDataLen )
{
assert(conn == m_pConnection);
if (dwDataLen < sizeof(SGameMsgHead))
{
WarningLn("Package length is too short.");
return;
}
Assert(pData != NULL);
SGameMsgHead* head = (SGameMsgHead*)pData;
MsgKey msgKey(head->byKeyModule, head->byKeyAction);
if (GetAnswerKeepAliveID() == msgKey.key)
{
m_bIsAnswer = true; // ๆฏๅฆๆๅๅบ
m_dwLastAnswerTime = ::GetTickCount(); // ๆๅๆถๅฐๅฟ่ทณTickๆถ้ด
}
else
{
m_Processer.Process((TConn*)this, pData, dwDataLen);
}
m_br.OnRecvData(dwDataLen); // ๆต้่ฎฐๅฝ ๆฅๆถ
}
// ๅค็ๆชๆณจๅ็ๆถๆฏ๏ผๆฏๅฆ่ฆ่ฝฌๅ็ๆถๆฏ๏ผ
virtual void UnHandled(LPVOID pData, DWORD dwDataLen)
{
SGameMsgHead* head = (SGameMsgHead*)pData;
char szBuf[256];
sprintf(szBuf, "UnKnown msg: SrcEndPoint=%d, DestEndPoint=%d, byKeyModule=%d, byKeyAction=%d !",
head->SrcEndPoint, head->DestEndPoint, head->byKeyModule, head->byKeyAction);
ErrorLn(szBuf);
}
protected:
// ๆต้่ฎฐๅฝ ๅ้
virtual void OnSendData(DWORD dwDataLen) { m_br.OnSendData(dwDataLen); }
// ๅๅฟ่ทณๅๅคๅ
็ID
virtual WORD GetAnswerKeepAliveID() = 0;
protected:
/*******************************************************************/
// ้ด้ๆถ้ด๏ผ่ฟ้็ปๅบ้ป่ฎคๅผ
/*******************************************************************/
// ไธคๆฌกKeepAliveๆขๆต้ด็ๆถ้ด้ด้๏ผๅไฝ๏ผๆฏซ็ง
virtual DWORD GetKeepAliveInterval() { return 2 * 1000; }
// ่ฟๆฅๅ
่ฎธ็ๆๅคง่ถ
ๆถๆถ้ด๏ผๅไฝ๏ผๆฏซ็ง
virtual DWORD GetMaxTimeout() { return 120 * 1000; }
// ้่ฟ็ๆถ้ด้ด้๏ผๅไฝ๏ผๆฏซ็ง
virtual DWORD GetReconnectInterval() { return 10 * 1000; }
/********************************************************************/
protected:
Processer<TConn>& m_Processer; // ๆถๆฏๅๅๅค็ๅจ
ByteRecord& m_br; // ๆต้่ฎฐๅฝๅจ๏ผ็ฑๅค้จๆณจๅ
ฅ
};
|
[
"[email protected]"
] | |
7668184e8ee846b75d84df3a534b4e3f2c0c70eb
|
fa6810e7a7499428ee9bbf955d181c662975a950
|
/LdsCdma_v1/LdsCdma_v1/stdafx.cpp
|
cbf4c4771c0acf510b1581e3fc71433fa0e179e0
|
[] |
no_license
|
LikeFishInWater/vs2010
|
8d57d94e6c1aef7e6c537e664f85d82f2182aca3
|
b9610597fb11b947dac4d2fddac8444934e6b6fb
|
refs/heads/master
| 2021-01-12T05:47:59.958110 | 2016-12-23T06:31:30 | 2016-12-23T06:31:30 | 77,201,661 | 1 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 261 |
cpp
|
// stdafx.cpp : ๅชๅ
ๆฌๆ ๅๅ
ๅซๆไปถ็ๆบๆไปถ
// LdsCDMA_v2.pch ๅฐไฝไธบ้ข็ผ่ฏๅคด
// stdafx.obj ๅฐๅ
ๅซ้ข็ผ่ฏ็ฑปๅไฟกๆฏ
#include "stdafx.h"
// TODO: ๅจ STDAFX.H ไธญๅผ็จไปปไฝๆ้็้ๅ ๅคดๆไปถ๏ผ
//่ไธๆฏๅจๆญคๆไปถไธญๅผ็จ
|
[
"[email protected]"
] | |
19e180688b2e13d26465f3243de730af52180d20
|
67baab02cfda6c54a287d63d0874824cf15f3ba6
|
/codeforces/1213e.cpp
|
6a27a0b056fa1a6b735cf3ccf8c2b29c7318410e
|
[
"MIT"
] |
permissive
|
sogapalag/problems
|
a14eedd8cfcdb52661479c8c90e08737aaeeb32b
|
0ea7d65448e1177f8b3f81124a82d187980d659c
|
refs/heads/master
| 2021-01-12T17:49:52.007234 | 2020-08-18T14:51:40 | 2020-08-18T14:51:40 | 71,629,601 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 878 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
string s,t;
cin >> s >> t;
auto ck = [&](string e){
return e.find(s) == string::npos && e.find(t) == string::npos;
};
auto rep = [](int n, string s){
for (int _ = 0; _ < n; _++) {
cout << s;
}
};
cout << "YES\n";
// no ->
if (ck("abca")) {
rep(n, "abc"); return;
}
// no <-
if (ck("cbac")) {
rep(n, "cba"); return;
}
// no ca
if (ck("aabbcc")) {
rep(n,"a"); rep(n,"b"); rep(n, "c"); return;
}
if (ck("bbccaa")) {
rep(n, "b"); rep(n, "c"); rep(n, "a"); return;
}
if (ck("ccaabb")) {
rep(n, "c"); rep(n, "a"); rep(n, "b"); return;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
|
[
"[email protected]"
] | |
f6be2f7e2c4256f853b48a81b426a2007cbddc76
|
6ef53083d8de65d54bc20ec1a06060458ec92ebe
|
/2.1/2.1.21/test2121.cpp
|
d1c6bda83a0c90aecb58cf72e67444c076a628f4
|
[] |
no_license
|
lanecoder/leetcode
|
fa5c59dfd2344412bf8902dc1f68b02698478f31
|
419c9f814d25e54682fe13c658801a3c23ace239
|
refs/heads/master
| 2020-03-19T23:38:23.329400 | 2018-07-21T10:43:06 | 2018-07-21T10:43:06 | 137,013,712 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 783 |
cpp
|
#include<iostream>
#include<vector>
//https://www.cnblogs.com/grandyang/p/4266812.html
using namespace std;
class Solution{
public:
int cirtravel(vector<int> & gas, vector<int> & cost){
int cir = gas.size();
int total = 0;
int sum = 0;
int start = 0;
for(int i = 0;i<cir;++i){
total += (gas[i]-cost[i]);
sum += (gas[i]-cost[i]);
if(sum < 0){
sum = 0;
start = i+1;
}
}
return (total<0)?-1:start;
}
};
int main(){
//int arr[8] = {1,3,4,2,1,6,3,4};
//int arr1[8] = {1,1,2,1,1,3,1,4};
int arr[8] = {5,3,2,4,1,6,3,4};
int arr1[8] = {4,3,5,5,2,3,2,4};
vector<int> ga(arr, arr+8);
vector<int> co(arr1, arr1+8);
Solution s;
int result = s.cirtravel(ga,co);
cout<<result<<endl;
return 0;
}
|
[
"[email protected]"
] | |
11a13c7674afb6de4a851f4b28411d56a0906682
|
729ed630d494aa1a9fec1202e24f5f91928ba62b
|
/EzCad3_VS2015/dlglicense.cpp
|
a52ee879751ede64e1a4435f514ff5a58628453e
|
[] |
no_license
|
lQLI/EzCad3_VS2015
|
ff8bb6a188d0d8279b9c30f2f07611c4d5391d00
|
67c80ef32d5da4988691dd578fdfa563749fbd65
|
refs/heads/master
| 2022-02-25T10:56:12.005977 | 2018-11-21T07:34:53 | 2018-11-21T07:34:53 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,795 |
cpp
|
// dlglicense.cpp : implementation file
//
#include "stdafx.h"
#include "EzCad3_VS2015.h"
#include "dlglicense.h"
#include "qglobal.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgLicense dialog
CDlgLicense::CDlgLicense(CWnd* pParent /*=NULL*/)
: CDialog(CDlgLicense::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgLicense)
m_strLice = _T("");
//}}AFX_DATA_INIT
}
void CDlgLicense::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgLicense)
DDX_Text(pDX, IDC_EDIT1, m_strLice);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgLicense, CDialog)
//{{AFX_MSG_MAP(CDlgLicense)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgLicense message handlers
BOOL CDlgLicense::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
GetDlgItem(IDOK)->SetWindowText(QGlobal::gf_Str(_T("IAGREE"),_T("I agree")));
GetDlgItem(IDCANCEL)->SetWindowText(QGlobal::gf_Str(_T("IDONTAGREE"),_T("I don't agree")));
if( m_strLice .IsEmpty() )
{
m_strLice=_T("END-USER LICENSE AGREEMENT FOR THIS SOFTWARE\r\n");
m_strLice+=_T("Important - read carefully:\r\n");
m_strLice+=_T("This End-User License Agreement (\"EULA\") is a legal agreement between you (either an individual or a single entity) and Beijing JCZ CO. Ltd for the software product identified above, which includes computer software and may include associated media, printed materials, and \"online\" or electronic documentation (\"SOFTWARE PRODUCT\"). By installing, copying, or otherwise using the SOFTWARE PRODUCT, you agree to be bound by the terms of this EULA. If you do not agree to the terms of this EULA, do not install or use the SOFTWARE PRODUCT.\r\n");
m_strLice+=_T("SOFTWARE PRODUCT LICENSE\r\n");
m_strLice+=_T("The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.\r\n");
m_strLice+=_T("1. GRANT OF LICENSE. This EULA grants you the following rights:\r\n");
m_strLice+=_T(" You can install one copy of this software product on a single computer.\r\n");
m_strLice+=_T("2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS.\r\n");
m_strLice+=_T(" Limitations on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT. Separation of Components.\r\n");
m_strLice+=_T(" The SOFTWARE PRODUCT is licensed as a single product. Its component parts may not be separated for use on more than one computer.Rental. You may not rent, lease or lend the SOFTWARE PRODUCT.\r\n");
m_strLice+=_T(" Software Transfer.\r\n");
m_strLice+=_T(" You may permanently transfer all of your rights under this EULA, * provided that:\r\n");
m_strLice+=_T(" 1) the recipient agrees to the terms of this EULA.\r\n");
m_strLice+=_T(" 2) You must remove this software product from your computer and no copy of this SOFTWARE PRODUCT should be kept.\r\n");
m_strLice+=_T(" 3) All componets of this SOFTWARE PRODUCT(includes computer software, associated media, printed materials, any update vertion of this SOFTWARE PRODUCT, and this EULA) must transfer to recipient. if this SOFTWARE PRODUCT has been updated, all previous vertion of this SOFTWARE PRODUCT should be transfered to the recipient also.\r\n");
m_strLice+=_T("3. COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT(including but not limited to any images, photographs, animations,video, audio, music, text, and \"applets\" incorporated into the SOFTWARE PRODUCT), the accompanying printed materials, and any copies of the SOFTWARE PRODUCT are owned by the BJJCZ. The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, you must treat the SOFTWARE PRODUCT like any other copyrighted material except that you may install the SOFTWARE PRODUCT on a single computer provided you keep the original solely for backup or archival purposes.\r\n");
m_strLice+=_T("4.NO WARRANTY. The Software is being delivered to you \"AS IS\" and BJJCZ makes no warranty as to its use or performance. BJJCZ AND ITS DISTRIBUTORS DO NOT AND CANNOT WARRANT THE PERFORMANCE OR RESULTS YOU MAY OBTAIN BY USING THE SOFTWARE. EXCEPT FOR ANY WARRANTY, CONDITION, REPRESENTATION OR TERM TO THE EXTENT TO WHICH THE SAME CANNOT OR MAY NOT BE EXCLUDED OR LIMITED BY LAW APPLICABLE TO YOU IN YOUR JURISDICTION, BJJCZ AND ITS DISTRIBUTORS MAKE NO WARRANTIES CONDITIONS, REPRESENTATIONS, OR TERMS (EXPRESS OR IMPLIED WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE) AS TO ANY MATTER INCLUDING WITHOUT LIMITATION NON-INFRINGEMENT OF THIRD PARTY RIGHTS, MERCHANTABILITY, INTEGRATION, SATISFACTORY QUALITY, OR FITNESS FOR ANY PARTICULAR PURPOSE.\r\n");
m_strLice+=_T("5.IMITATION OF LIABILITY. IN NO EVENT WILL BJJCZ OR ITS DISTRIBUTORS BE LIABLE TO YOU FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS, EVEN IF A BJJCZ REPRESENTATIVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, DAMAGES, CLAIMS OR COSTS OR FOR ANY CLAIM BY ANY THIRD PARTY. THE FOREGOING LIMITATIONS AND EXCLUSIONS APPLY TO THE EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION. BJJCZ AGGREGATE LIABILITY AND THAT OF ITS DISTRIBUTORS UNDER OR IN CONNECTION WITH THIS AGREEMENT SHALL BE LIMITED TO THE AMOUNT PAID FOR THE SOFTWARE, IF ANY. \r\n");
m_strLice+=_T("6.TERMINATION. This License Agreement shall terminate automatically if you fail to comply with the limitations described in this license. No notice shall be required from BJJCZ to effectuate such termination. Upon termination, you must destroy all copies of the Software and Documentation. \r\n");
m_strLice+=_T("7.APPLICABLE LAW. The Product is protected by <<INTELLECTUAL PROPERTY LAWS AND TREATIES>>,<<COPYRIGHT LAW>>,<<EXCLUSIVE LAW>> and ohter relative laws.If you acquired the SOFTWARE in China, this EULA is governed by the laws of the China. If you acquired the SOFTWARE outside of the China, then local laws may apply.\r\n");
m_strLice+=_T("Should you have any questions concerning this EULA, or if you desire to contact BJJCZ for any reason, please contact BJJCZ\r\n");
m_strLice+=_T("http://www.bjjcz.com\r\n");
m_strLice+=_T("Telephone : (086) 010-64426995. The phone may change in the future, check the web please.\r\n");
}
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
|
[
"[email protected]"
] | |
b21d577804c5d01220d57126f829e9018c0bacd8
|
c776476e9d06b3779d744641e758ac3a2c15cddc
|
/examples/litmus/c/run-scripts/tmp_1/S+dmb.sy+ctrlisb.c.cbmc.cpp
|
986d1f5958f5eff8873b23ffed80bb158678b04c
|
[] |
no_license
|
ashutosh0gupta/llvm_bmc
|
aaac7961c723ba6f7ffd77a39559e0e52432eade
|
0287c4fb180244e6b3c599a9902507f05c8a7234
|
refs/heads/master
| 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 |
C++
|
UTF-8
|
C++
| false | false | 25,801 |
cpp
|
// 0:vars:2
// 2:atom_1_X0_1:1
// 3:thr0:1
// 4:thr1:1
#define ADDRSIZE 5
#define NPROC 3
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !33, metadata !DIExpression()), !dbg !42
// br label %label_1, !dbg !43
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !41), !dbg !44
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !34, metadata !DIExpression()), !dbg !45
// call void @llvm.dbg.value(metadata i64 2, metadata !37, metadata !DIExpression()), !dbg !45
// store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !46
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 2;
mem(0,cw(1,0)) = 2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !47
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,2+0));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cw(1,4+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,2+0));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(cdy[1] >= cr(1,4+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !38, metadata !DIExpression()), !dbg !48
// call void @llvm.dbg.value(metadata i64 1, metadata !40, metadata !DIExpression()), !dbg !48
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !49
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !50
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !53, metadata !DIExpression()), !dbg !68
// br label %label_2, !dbg !50
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !66), !dbg !70
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !56, metadata !DIExpression()), !dbg !71
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !58, metadata !DIExpression()), !dbg !71
// %conv = trunc i64 %0 to i32, !dbg !54
// call void @llvm.dbg.value(metadata i32 %conv, metadata !54, metadata !DIExpression()), !dbg !68
// %tobool = icmp ne i32 %conv, 0, !dbg !55
// br i1 %tobool, label %if.then, label %if.else, !dbg !57
old_cctrl = cctrl[2];
cctrl[2] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[2] >= old_cctrl);
ASSUME(cctrl[2] >= creg_r0);
ASSUME(cctrl[2] >= 0);
if((r0!=0)) {
goto T2BLOCK2;
} else {
goto T2BLOCK3;
}
T2BLOCK2:
// br label %lbl_LC00, !dbg !58
goto T2BLOCK4;
T2BLOCK3:
// br label %lbl_LC00, !dbg !59
goto T2BLOCK4;
T2BLOCK4:
// call void @llvm.dbg.label(metadata !67), !dbg !79
// call void (...) @isb(), !dbg !61
// isb: Guess
cisb[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cisb[2] >= cdy[2]);
ASSUME(cisb[2] >= cctrl[2]);
ASSUME(cisb[2] >= caddr[2]);
ASSUME(creturn[2] >= cisb[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !59, metadata !DIExpression()), !dbg !81
// call void @llvm.dbg.value(metadata i64 1, metadata !61, metadata !DIExpression()), !dbg !81
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !63
// ST: Guess
iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0);
cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0)] == 2);
ASSUME(active[cw(2,0)] == 2);
ASSUME(sforbid(0,cw(2,0))== 0);
ASSUME(iw(2,0) >= 0);
ASSUME(iw(2,0) >= 0);
ASSUME(cw(2,0) >= iw(2,0));
ASSUME(cw(2,0) >= old_cw);
ASSUME(cw(2,0) >= cr(2,0));
ASSUME(cw(2,0) >= cl[2]);
ASSUME(cw(2,0) >= cisb[2]);
ASSUME(cw(2,0) >= cdy[2]);
ASSUME(cw(2,0) >= cdl[2]);
ASSUME(cw(2,0) >= cds[2]);
ASSUME(cw(2,0) >= cctrl[2]);
ASSUME(cw(2,0) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0) = 1;
mem(0,cw(2,0)) = 1;
co(0,cw(2,0))+=1;
delta(0,cw(2,0)) = -1;
ASSUME(creturn[2] >= cw(2,0));
// %cmp = icmp eq i32 %conv, 1, !dbg !64
// %conv1 = zext i1 %cmp to i32, !dbg !64
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !62, metadata !DIExpression()), !dbg !68
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !63, metadata !DIExpression()), !dbg !84
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !65, metadata !DIExpression()), !dbg !84
// store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !66
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= max(creg_r0,0));
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==1);
mem(2,cw(2,2)) = (r0==1);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// ret i8* null, !dbg !67
ret_thread_2 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !94, metadata !DIExpression()), !dbg !120
// call void @llvm.dbg.value(metadata i8** %argv, metadata !95, metadata !DIExpression()), !dbg !120
// %0 = bitcast i64* %thr0 to i8*, !dbg !65
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #6, !dbg !65
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !96, metadata !DIExpression()), !dbg !122
// %1 = bitcast i64* %thr1 to i8*, !dbg !67
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #6, !dbg !67
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !100, metadata !DIExpression()), !dbg !124
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !101, metadata !DIExpression()), !dbg !125
// call void @llvm.dbg.value(metadata i64 0, metadata !103, metadata !DIExpression()), !dbg !125
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !70
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !104, metadata !DIExpression()), !dbg !127
// call void @llvm.dbg.value(metadata i64 0, metadata !106, metadata !DIExpression()), !dbg !127
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !72
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !107, metadata !DIExpression()), !dbg !129
// call void @llvm.dbg.value(metadata i64 0, metadata !109, metadata !DIExpression()), !dbg !129
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !74
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #6, !dbg !75
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #6, !dbg !76
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !77, !tbaa !78
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r2 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r2 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r2 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// %call6 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !82
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !83, !tbaa !78
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r3 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r3 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r3 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !84
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !111, metadata !DIExpression()), !dbg !141
// %4 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !86
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r4 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r4 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r4 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %4, metadata !113, metadata !DIExpression()), !dbg !141
// %conv = trunc i64 %4 to i32, !dbg !87
// call void @llvm.dbg.value(metadata i32 %conv, metadata !110, metadata !DIExpression()), !dbg !120
// %cmp = icmp eq i32 %conv, 2, !dbg !88
// %conv8 = zext i1 %cmp to i32, !dbg !88
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !114, metadata !DIExpression()), !dbg !120
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !116, metadata !DIExpression()), !dbg !145
// %5 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !90
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r5 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r5 = buff(0,2);
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r5 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i64 %5, metadata !118, metadata !DIExpression()), !dbg !145
// %conv12 = trunc i64 %5 to i32, !dbg !91
// call void @llvm.dbg.value(metadata i32 %conv12, metadata !115, metadata !DIExpression()), !dbg !120
// %and = and i32 %conv8, %conv12, !dbg !92
creg_r6 = max(max(creg_r4,0),creg_r5);
ASSUME(active[creg_r6] == 0);
r6 = (r4==2) & r5;
// call void @llvm.dbg.value(metadata i32 %and, metadata !119, metadata !DIExpression()), !dbg !120
// %cmp13 = icmp eq i32 %and, 1, !dbg !93
// br i1 %cmp13, label %if.then, label %if.end, !dbg !95
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r6);
ASSUME(cctrl[0] >= 0);
if((r6==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([101 x i8], [101 x i8]* @.str.1, i64 0, i64 0), i32 noundef 55, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #7, !dbg !96
// unreachable, !dbg !96
r7 = 1;
T0BLOCK2:
// %6 = bitcast i64* %thr1 to i8*, !dbg !99
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %6) #6, !dbg !99
// %7 = bitcast i64* %thr0 to i8*, !dbg !99
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %7) #6, !dbg !99
// ret i32 0, !dbg !100
ret_thread_0 = 0;
ASSERT(r7== 0);
}
|
[
"[email protected]"
] | |
72de2ae3ed62a798611477d5ece21368fbb949e8
|
bc66832bae1a62daaade56c49ebf3fc2d59cfa60
|
/Coding_Problem/Coding_Problem_In_C/FunctionalTail.cpp
|
7946c3c1ca5bd9a3f672634317ac06e927cfcad8
|
[] |
no_license
|
surplusus/Database_ProblemSol
|
9d9c518f557ebd2e96b46a68b0aa4a43ca9abdad
|
6cd62e436a0d4bb1e0906e42891d3305e93d87a4
|
refs/heads/master
| 2022-12-09T14:17:10.462019 | 2021-07-14T12:05:21 | 2021-07-14T12:05:21 | 187,649,839 | 0 | 0 | null | 2022-12-07T17:59:32 | 2019-05-20T13:51:12 |
C++
|
UTF-8
|
C++
| false | false | 424 |
cpp
|
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
long long FactorialRec(int n) {
if (n == 1)
return 1;
else
return n * FactorialRec(n - 1);
}
long long FactorialTailRec(int n, int res) {
if (n == 1)
return res;
return FactorialTailRec(n - 1, res*n);
}
long long FactorialTail(int n) {
return FactorialTailRec(n, 1);
}
int main()
{
cout << FactorialTail(1000)<<endl;
return 0;
}
|
[
"Inha@DESKTOP-CP8BH8U"
] |
Inha@DESKTOP-CP8BH8U
|
5d6e8a36c6d315960364ba6f605d6d7bcc2cf468
|
fb0370b675eb6cce3432de4e35a8577cc3692dc9
|
/UVA/11090/20276398_AC_100ms_0kB.cpp
|
b4cc4477aff5619f14501a0a732ef387df639f64
|
[] |
no_license
|
qq734628996/ac-code
|
752b84911b5814d233ca1a3a9f65895acff8e678
|
9306d4c2db8d845dc5c5a1f6be723dbf6e0aae53
|
refs/heads/master
| 2021-08-18T11:05:00.311669 | 2020-05-29T14:08:38 | 2020-05-29T14:08:38 | 188,193,391 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,465 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i = 0; i < n; i++)
#define PER(i,n) for(int i = n-1; i >= 0; i--)
#define FOR(i,l,r) for(int i = l; i <= r; i++)
#define ROF(i,l,r) for(int i = r; i >= l; i--)
#define DEBUG(x) cout << #x << "=" << x << endl;
#define SHOW1(A,n) { REP(i,n-1) printf("%d ", A[i]); printf("%d\n", A[n-1]); }
#define SHOW2(A,m,n) { REP(i,m) { REP(j,n-1) printf("%d ", A[i][j]); printf("%d\n", A[i][n-1]); } }
#define pb push_back
#define fi first
#define se second
#define ALL(x) x.begin(),x.end()
#define SZ(x) (int)((x).size())
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
const int INF = 0x3f3f3f3f, MOD = 1000000007;
const double PI = acos(-1), EPS = 1e-15;
const int MAXN = 1e2+9, MAXM = 1e5+9;
int to[MAXM],f[MAXN],nxt[MAXM],tot;
double dis[MAXM];
void init(){ tot=0; memset(f,-1,sizeof(f)); }
void add(int u, int v, int w)
{
to[tot]=v;
dis[tot]=w;
nxt[tot]=f[u];
f[u]=tot++;
}
int n,m,inq[MAXN];
double d[MAXN];
bool spfa()
{
memset(inq,0,sizeof(inq));
memset(d,0,sizeof(d));
int cnt=0;
queue<int> Q;
FOR(i,1,n) Q.push(i);
while (!Q.empty()) {
int u=Q.front(); Q.pop();
inq[u]=0;
for (int i=f[u]; ~i; i=nxt[i]) {
int v=to[i];
double w=dis[i];
if (d[v]>d[u]+w) {
d[v]=d[u]+w;
if (!inq[v]) {
inq[v]=1;
Q.push(v);
if (++cnt>2*(n+m)) return true;
}
}
}
}
return false;
}
bool jdg(double x)
{
REP(i,tot) dis[i]-=x;
bool res=spfa();
REP(i,tot) dis[i]+=x;
return res;
}
int main()
{
#ifdef LOCAL
freopen("i.txt", "r", stdin);
//freopen("o.txt", "w", stdout);
#endif //LOCAL
int T; scanf("%d", &T);
FOR(kase,1,T) {
init();
scanf("%d%d", &n,&m);
int ma=0;
REP(i,m) {
int x,y,z; scanf("%d%d%d", &x,&y,&z);
add(x,y,z);
ma=max(ma,z);
}
printf("Case #%d: ", kase);
if (!jdg(ma+1)) puts("No cycle found.");
else {
double l=0, r=ma;
while (r-l>1e-3) {
double m=(l+r)/2;
if (jdg(m)) r=m;
else l=m;
}
printf("%.2f\n", (l+r)/2);
}
}
return 0;
}
|
[
"[email protected]"
] | |
7ec5cda7f4c66ea372dcc3c14b3e2aa19a505158
|
26d98b57f908d905cf8d8b3b0a568c5bb23b4d40
|
/addons/cmx_imgui_app/src/gfx_ui.h
|
fb0b2de2060c7200bba338718e2bd7a96131fb7d
|
[
"MIT"
] |
permissive
|
colormotor/colormotor
|
821c755c53ff3679ce111c4a8e26323993ad1ae7
|
645ba3e173cd001e5be60ff5cca86ecc73131fc1
|
refs/heads/master
| 2021-06-06T11:26:34.664417 | 2021-05-10T13:34:11 | 2021-05-10T13:34:11 | 33,570,479 | 5 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,817 |
h
|
/********************************************************************
--------------------------------------------------------------------
-- _,(_)._
-- ___,(_______). ____
-- ,'__. \ /\___\-.
-- /,' / \ / / \
-- | | | |,' / \
-- \`.| / ___|________
-- `. : : / gfx_ui
-- `. :.,' A immediate mode 2d graphics manipulation UI
-- `-.________,-' Built on top of IMGUI
-- ยฉ Daniel Berio
-- http://www.enist.org
-- [email protected]
--
--------------------------------------------------------------------
********************************************************************/
#pragma once
#include "imgui.h"
#include "gfx_ui_config.h"
#include <stdlib.h>
#include <vector>
#include <string>
#include <sstream>
namespace ui
{
enum
{
DRAGGER_CIRCLE = 0,
DRAGGER_SQUARE = 1
};
struct Trans2d
{
Trans2d() {}
Trans2d( const ImVec2& x, const ImVec2& y, const ImVec2& pos)
: x(x), y(y), pos(pos) {}
#ifdef UI_TRANS2D_CLASS_EXTRA
UI_TRANS2D_CLASS_EXTRA
#endif
ImVec2 x;
ImVec2 y;
ImVec2 pos;
};
struct Rect
{
Rect() {}
Rect( const ImVec2& min, const ImVec2& max )
: min(min), max(max) {}
#ifdef UI_RECT_CLASS_EXTRA
UI_RECT_CLASS_EXTRA
#endif
bool contains( const ImVec2& p ) const { return ( p.x >= min.x && p.y >= min.y
&& p.x <= max.x && p.y <= max.y ); }
ImVec2 min;
ImVec2 max;
};
struct Config
{
Config()
{
rounding = 2.0;
draggerSize = 4.0;
lineColor = 0xff666666;
hoverColor = 0xff0000ff;
selectedColor = 0xff0033ff;
color=0xffffcd00;
//color=0xff666666;
textColor=0xff333333;
}
float rounding;
float draggerSize;
ImU32 lineColor;
ImU32 hoverColor;
ImU32 selectedColor;
ImU32 color;
ImU32 textColor;
};
extern Config config;
/// Returns true if the IMGUI/gfx_ui have focus
/// Since gfx_ui creates a "full screen" window to handle interactions through IMGUI,
/// you should use this rather than ImGui::GetIO().WantCaptureMouse to check weather
/// your application should handle mouse events
bool hasFocus();
bool isMouseDown();
/// Initialization, starts up the font
/// This function should be called BEFORE the IMGUI texture atlas is created
/// And AFTER the default IMGUI texture has been loaded.
/// Should find a less restrictive way to handle this.
void init( float iconSize=20.0, const std::string& iconFontPath="");
/// The UI should be called withing these begin end blocks
void begin( const std::string& name="gfx_ui" );
void end();
/// Will return true if the previous widget call has caught an interaction
bool modified();
bool modifierShift();
bool modifierAlt();
/// Dragger widget
ImVec2 dragger( int index, ImVec2 pos, bool selected=false, float size=-1. );
/// Highlights a dragger
void highlightDragger( const ImVec2& pos, float size=-1. );
/// Draw a line from a to b
void line( const ImVec2& a, const ImVec2& b, ImColor clr=ImColor(-1,-1,-1,1) );
// Draw text string
void text( ImVec2 pos, const std::string& str, ImColor clr=ImColor(-1,-1,-1,1) );
/// Angle and length handle widget
ImVec2 lengthHandle( int index, ImVec2 thetaLen, float startTheta, const ImVec2& pos, const ImVec2& minThetaLen, const ImVec2& maxThetaLen, bool selected=false );
/// Angle handle widget
float handle( int index, float ang, const ImVec2& pos, float length, float startTheta=0.0f, float minTheta=0.0f, float maxTheta=0.0f, bool selected=false );
/// Simple affine transform widget (two axes, centered)
Trans2d affineSimple( int index, Trans2d m, bool selected=false, float scale=1. );
/// Creates a draggable rect for selection, see demo() for example usage
Rect selector();
/// Returns current mouse delta
ImVec2 dragDelta();
/// Creates a font-icon toolbar (not necessary to call between begin and end)
int toolbar( const std::string& title,
const std::string& items,
int selectedItem,
bool horizontal=false,
bool showAscii=false,
const std::vector<std::string>& tooltips=std::vector<std::string>());
void demo();
}
|
[
"[email protected]"
] | |
ee89026ead1f61a425b208ad0ec09494e724c586
|
f033d578e4fa6ec7ee8f2c2fbf34b4c14b16cc8a
|
/csi2172/A3/a3orig/MAIN_NEWrev.CPP
|
ff5c11e1c43ba3c8b10815dd885aff670a7e85f4
|
[] |
no_license
|
epistemik/Courses
|
c8d2c6f6756acc39d62ee92b5fc58c1cfffbab56
|
3e63c15ce2fb87f11c5ab28eb5dac14875bc060c
|
refs/heads/master
| 2021-06-08T19:50:11.849327 | 2021-04-14T18:10:13 | 2021-04-14T18:10:13 | 146,174,580 | 1 | 0 | null | null | null | null |
MacCentralEurope
|
C++
| false | false | 895 |
cpp
|
// NAME: Mark Sattolo
// STUDENT #: 428500
// SECTION: CSI 2172A
// MARKING SECTION: A4
#include <stdlib.h>
#include <iostream.h>
#include "test.h"
#include โheap.hโ
#include "aheap.h"
bool lt(const test_class& c1, const test_class& c2)
{ return *const_cast<test_class&>(c1) < *const_cast<test_class&>(c2) ; }
int rrr(int n)
{
#if defined(__GNUG__)
return random() % n;
#else
return random(n);
#endif
}
int main(int argc, char* argv[])
{
me(cout) ;
array_heap<test_class> H(lt, array_heap<test_class>::SMALLER_FIRST);
for(int i=1; i< argc; ++i)
{
heap<test_class>::handle& h1 = H.push(test_class(atof(argv[i])));
if (i % 2 == 0)
{
int k = rrr(10);
*const_cast<test_class&>(*h1) += k;
H.priority_change(h1);
}
}
H.print(cout);
cout << "-----" << endl;
while(!H.empty())
{
cout << H.top() << ' ';
H.pop();
}
cout << endl;
return 0;
}
|
[
"[email protected]"
] | |
811630b60211ace372462c41669f95d3c3ee4aef
|
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
|
/google/cloud/aiplatform/v1/model_garden_connection.h
|
9129604b2ec9c5a5e2d4b88385d105f706f40e59
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
googleapis/google-cloud-cpp
|
b96a6ee50c972371daa8b8067ddd803de95f54ba
|
178d6581b499242c52f9150817d91e6c95b773a5
|
refs/heads/main
| 2023-08-31T09:30:11.624568 | 2023-08-31T03:29:11 | 2023-08-31T03:29:11 | 111,860,063 | 450 | 351 |
Apache-2.0
| 2023-09-14T21:52:02 | 2017-11-24T00:19:31 |
C++
|
UTF-8
|
C++
| false | false | 8,867 |
h
|
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/aiplatform/v1/model_garden_service.proto
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_AIPLATFORM_V1_MODEL_GARDEN_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_AIPLATFORM_V1_MODEL_GARDEN_CONNECTION_H
#include "google/cloud/aiplatform/v1/internal/model_garden_retry_traits.h"
#include "google/cloud/aiplatform/v1/model_garden_connection_idempotency_policy.h"
#include "google/cloud/backoff_policy.h"
#include "google/cloud/internal/retry_policy_impl.h"
#include "google/cloud/options.h"
#include "google/cloud/status_or.h"
#include "google/cloud/version.h"
#include <google/cloud/aiplatform/v1/model_garden_service.pb.h>
#include <memory>
#include <string>
namespace google {
namespace cloud {
namespace aiplatform_v1 {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
/// The retry policy for `ModelGardenServiceConnection`.
class ModelGardenServiceRetryPolicy : public ::google::cloud::RetryPolicy {
public:
/// Creates a new instance of the policy, reset to the initial state.
virtual std::unique_ptr<ModelGardenServiceRetryPolicy> clone() const = 0;
};
/**
* A retry policy for `ModelGardenServiceConnection` based on counting errors.
*
* This policy stops retrying if:
* - An RPC returns a non-transient error.
* - More than a prescribed number of transient failures is detected.
*
* In this class the following status codes are treated as transient errors:
* - [`kUnavailable`](@ref google::cloud::StatusCode)
*/
class ModelGardenServiceLimitedErrorCountRetryPolicy
: public ModelGardenServiceRetryPolicy {
public:
/**
* Create an instance that tolerates up to @p maximum_failures transient
* errors.
*
* @note Disable the retry loop by providing an instance of this policy with
* @p maximum_failures == 0.
*/
explicit ModelGardenServiceLimitedErrorCountRetryPolicy(int maximum_failures)
: impl_(maximum_failures) {}
ModelGardenServiceLimitedErrorCountRetryPolicy(
ModelGardenServiceLimitedErrorCountRetryPolicy&& rhs) noexcept
: ModelGardenServiceLimitedErrorCountRetryPolicy(rhs.maximum_failures()) {
}
ModelGardenServiceLimitedErrorCountRetryPolicy(
ModelGardenServiceLimitedErrorCountRetryPolicy const& rhs) noexcept
: ModelGardenServiceLimitedErrorCountRetryPolicy(rhs.maximum_failures()) {
}
int maximum_failures() const { return impl_.maximum_failures(); }
bool OnFailure(Status const& status) override {
return impl_.OnFailure(status);
}
bool IsExhausted() const override { return impl_.IsExhausted(); }
bool IsPermanentFailure(Status const& status) const override {
return impl_.IsPermanentFailure(status);
}
std::unique_ptr<ModelGardenServiceRetryPolicy> clone() const override {
return std::make_unique<ModelGardenServiceLimitedErrorCountRetryPolicy>(
maximum_failures());
}
// This is provided only for backwards compatibility.
using BaseType = ModelGardenServiceRetryPolicy;
private:
google::cloud::internal::LimitedErrorCountRetryPolicy<
aiplatform_v1_internal::ModelGardenServiceRetryTraits>
impl_;
};
/**
* A retry policy for `ModelGardenServiceConnection` based on elapsed time.
*
* This policy stops retrying if:
* - An RPC returns a non-transient error.
* - The elapsed time in the retry loop exceeds a prescribed duration.
*
* In this class the following status codes are treated as transient errors:
* - [`kUnavailable`](@ref google::cloud::StatusCode)
*/
class ModelGardenServiceLimitedTimeRetryPolicy
: public ModelGardenServiceRetryPolicy {
public:
/**
* Constructor given a `std::chrono::duration<>` object.
*
* @tparam DurationRep a placeholder to match the `Rep` tparam for @p
* duration's type. The semantics of this template parameter are
* documented in `std::chrono::duration<>`. In brief, the underlying
* arithmetic type used to store the number of ticks. For our purposes it
* is simply a formal parameter.
* @tparam DurationPeriod a placeholder to match the `Period` tparam for @p
* duration's type. The semantics of this template parameter are
* documented in `std::chrono::duration<>`. In brief, the length of the
* tick in seconds, expressed as a `std::ratio<>`. For our purposes it is
* simply a formal parameter.
* @param maximum_duration the maximum time allowed before the policy expires.
* While the application can express this time in any units they desire,
* the class truncates to milliseconds.
*
* @see https://en.cppreference.com/w/cpp/chrono/duration for more information
* about `std::chrono::duration`.
*/
template <typename DurationRep, typename DurationPeriod>
explicit ModelGardenServiceLimitedTimeRetryPolicy(
std::chrono::duration<DurationRep, DurationPeriod> maximum_duration)
: impl_(maximum_duration) {}
ModelGardenServiceLimitedTimeRetryPolicy(
ModelGardenServiceLimitedTimeRetryPolicy&& rhs) noexcept
: ModelGardenServiceLimitedTimeRetryPolicy(rhs.maximum_duration()) {}
ModelGardenServiceLimitedTimeRetryPolicy(
ModelGardenServiceLimitedTimeRetryPolicy const& rhs) noexcept
: ModelGardenServiceLimitedTimeRetryPolicy(rhs.maximum_duration()) {}
std::chrono::milliseconds maximum_duration() const {
return impl_.maximum_duration();
}
bool OnFailure(Status const& status) override {
return impl_.OnFailure(status);
}
bool IsExhausted() const override { return impl_.IsExhausted(); }
bool IsPermanentFailure(Status const& status) const override {
return impl_.IsPermanentFailure(status);
}
std::unique_ptr<ModelGardenServiceRetryPolicy> clone() const override {
return std::make_unique<ModelGardenServiceLimitedTimeRetryPolicy>(
maximum_duration());
}
// This is provided only for backwards compatibility.
using BaseType = ModelGardenServiceRetryPolicy;
private:
google::cloud::internal::LimitedTimeRetryPolicy<
aiplatform_v1_internal::ModelGardenServiceRetryTraits>
impl_;
};
/**
* The `ModelGardenServiceConnection` object for `ModelGardenServiceClient`.
*
* This interface defines virtual methods for each of the user-facing overload
* sets in `ModelGardenServiceClient`. This allows users to inject custom
* behavior (e.g., with a Google Mock object) when writing tests that use
* objects of type `ModelGardenServiceClient`.
*
* To create a concrete instance, see `MakeModelGardenServiceConnection()`.
*
* For mocking, see `aiplatform_v1_mocks::MockModelGardenServiceConnection`.
*/
class ModelGardenServiceConnection {
public:
virtual ~ModelGardenServiceConnection() = 0;
virtual Options options() { return Options{}; }
virtual StatusOr<google::cloud::aiplatform::v1::PublisherModel>
GetPublisherModel(
google::cloud::aiplatform::v1::GetPublisherModelRequest const& request);
};
/**
* A factory function to construct an object of type
* `ModelGardenServiceConnection`.
*
* The returned connection object should not be used directly; instead it
* should be passed as an argument to the constructor of
* ModelGardenServiceClient.
*
* The optional @p options argument may be used to configure aspects of the
* returned `ModelGardenServiceConnection`. Expected options are any of the
* types in the following option lists:
*
* - `google::cloud::CommonOptionList`
* - `google::cloud::GrpcOptionList`
* - `google::cloud::UnifiedCredentialsOptionList`
* - `google::cloud::aiplatform_v1::ModelGardenServicePolicyOptionList`
*
* @note Unexpected options will be ignored. To log unexpected options instead,
* set `GOOGLE_CLOUD_CPP_ENABLE_CLOG=yes` in the environment.
*
* @param location Sets the prefix for the default `EndpointOption` value.
* @param options (optional) Configure the `ModelGardenServiceConnection`
* created by this function.
*/
std::shared_ptr<ModelGardenServiceConnection> MakeModelGardenServiceConnection(
std::string const& location, Options options = {});
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace aiplatform_v1
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_AIPLATFORM_V1_MODEL_GARDEN_CONNECTION_H
|
[
"[email protected]"
] | |
18812427bc34a7629f63958435c32dcfdd22e395
|
418f420231f4a0ea5917b9cc11ef4e5ef4933c06
|
/M-Paradox/Network/Chat_Message.h
|
9e9515e88db9b62280c76b81bc06e2dacf2ba34a
|
[] |
no_license
|
yamamushi/M-Paradox
|
2d5210bdc2eed4f9483aa76a7345da431196f634
|
5e673ba68301b463b0005fada92048bfa1e36978
|
refs/heads/master
| 2020-12-24T17:45:31.271020 | 2013-05-21T18:17:29 | 2013-05-21T18:17:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,746 |
h
|
//
// Chat_Message.h
// M-Paradox
//
// Created by Jonathan Rumion on 5/21/13.
// Copyright (c) 2013 TAP. All rights reserved.
//
#ifndef M_Paradox_Chat_Message_h
#define M_Paradox_Chat_Message_h
#include <cstdio>
#include <cstdlib>
#include <cstring>
class chat_message
{
public:
enum { header_length = 4 };
enum { max_body_length = 512 };
chat_message()
: body_length_(0)
{
}
const char* data() const
{
return data_;
}
char* data()
{
return data_;
}
size_t length() const
{
return header_length + body_length_;
}
const char* body() const
{
return data_ + header_length;
}
char* body()
{
return data_ + header_length;
}
size_t body_length() const
{
return body_length_;
}
void body_length(size_t new_length)
{
body_length_ = new_length;
if (body_length_ > max_body_length)
body_length_ = max_body_length;
}
bool decode_header()
{
using namespace std; // For strncat and atoi.
char header[header_length + 1] = "";
strncat(header, data_, header_length);
body_length_ = atoi(header);
if (body_length_ > max_body_length)
{
body_length_ = 0;
return false;
}
return true;
}
void encode_header()
{
using namespace std; // For sprintf and memcpy.
char header[header_length + 1] = "";
sprintf(header, "%4d", (int)body_length_);
memcpy(data_, header, header_length);
}
private:
char data_[header_length + max_body_length];
size_t body_length_;
};
#endif
|
[
"[email protected]"
] | |
368c13c2e425850bdd2e0e51fecda50b91cd4dd5
|
478b209ebe00b694fe3a574be5a430b9989a12a0
|
/Friend Numbers (20).cpp
|
eb904147386202b0a08d6a736fa92ad9268a5d61
|
[] |
no_license
|
Woooosz/AlgorithmTrainSet
|
1902bf8ecdae83f929aa1e3901291f3fc335148f
|
b93f5f514c6eb22afc2c4ed9665d79a58595e2cc
|
refs/heads/master
| 2021-01-17T18:06:51.550741 | 2017-03-22T02:17:47 | 2017-03-22T02:17:47 | 71,051,233 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 627 |
cpp
|
#include <iostream>
#include <map>
using namespace std;
typedef map<int,int>::iterator itor;
int main () {
int n,t,m,sum = 0;
map<int,int> d;
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", &t);
while(t > 0) {
sum += (t % 10);
t /= 10;
}
d[sum]++;
sum = 0;
}
int f = 0;
printf("%d\n", d.size());
for(itor pi = d.begin(); pi != d.end(); ++pi) {
if(!f) {
printf("%d", pi->first);
f = 1;
} else {
printf(" %d", pi->first);
}
}
printf("\n");
return 0;
}
|
[
"[email protected]"
] | |
6b11dcf4abbaeac3a14368d69380d8d27e2e78de
|
259a47e4c6621139fab83c97f515da6d27d4c2be
|
/ELib/source/ENetwork/ENetPacketHandler.cpp
|
f6f121e12a914a45f31bdcf7603a0068da367153
|
[] |
no_license
|
Elandryl/ELib
|
1ed3d4f9bb7f350cd03c6c886bdd5db7df69fd60
|
d37674d6f01164bd29da1370069a320d674da99c
|
refs/heads/master
| 2021-01-09T20:35:19.332293 | 2019-06-10T16:11:20 | 2019-06-10T16:11:20 | 61,484,699 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,946 |
cpp
|
/**
@author Elandryl (Christophe.M).
@date 2019.
@brief Source for ENetPacketHandler Class.
*/
#include "ENetwork/ENetPacketHandler.h"
/**
@brief General scope for ELib components.
*/
namespace ELib
{
/**
@brief Generator for ENetPacketDisconnect. /!\ EError.
@param p_src ENetSocket source of ENetPacket.
@return Generated ENetPacketDisconnect on success.
@return nullptr on failure.
*/
ENetPacket *generateENetPacketDisconnect(ENetSocket *p_src)
{
ENetPacket *l_packet = nullptr;
mEERROR_R();
l_packet = new ENetPacketDisconnect(p_src);
if (nullptr == l_packet)
{
mEERROR_S(EERROR_MEMORY);
}
return (l_packet);
}
/**
@brief Generator for ENetPacketConnect. /!\ EError.
@param p_src ENetSocket source of ENetPacket.
@return Generated ENetPacketConnect on success.
@return nullptr on failure.
*/
ENetPacket *generateENetPacketConnect(ENetSocket *p_src)
{
ENetPacket *l_packet = nullptr;
mEERROR_R();
l_packet = new ENetPacketConnect(p_src);
if (nullptr == l_packet)
{
mEERROR_S(EERROR_MEMORY);
}
return (l_packet);
}
/**
@brief Generator for ENetPacketRawDatas. /!\ EError.
@param p_src ENetSocket source of ENetPacket.
@return Generated ENetPacketRawDatas on success.
@return nullptr on failure.
*/
ENetPacket *generateENetPacketRawDatas(ENetSocket *p_src)
{
ENetPacket *l_packet = nullptr;
mEERROR_R();
l_packet = new ENetPacketRawDatas(p_src);
if (nullptr == l_packet)
{
mEERROR_S(EERROR_MEMORY);
}
return (l_packet);
}
/**
@brief Constructor for ENetPacketHandler.
@details Add Basics ENetPacketGenerators.
*/
ENetPacketHandler::ENetPacketHandler() :
m_generators(),
m_packets(),
m_mutexPackets(nullptr)
{
m_generators[ENETPACKET_TYPE_DISCONNECT] = generateENetPacketDisconnect;
m_generators[ENETPACKET_TYPE_CONNECT] = generateENetPacketConnect;
m_generators[ENETPACKET_TYPE_RAW_DATAS] = generateENetPacketRawDatas;
}
/**
@brief Destructor for ENetPacketHandler.
@details Release its mutex.
*/
ENetPacketHandler::~ENetPacketHandler()
{
ReleaseMutex(m_mutexPackets);
CloseHandle(m_mutexPackets);
}
/**
@brief Singleton for ENetPacketHandler. /!\ EError.
@details Initialize its mutex.
@return ENetPacketHandler unique instance on success.
@return nullptr on failure.
*/
ENetPacketHandler *ENetPacketHandler::getInstance()
{
static ENetPacketHandler *l_instance = nullptr;
mEERROR_R();
if (nullptr == l_instance)
{
HANDLE l_mutex = nullptr;
l_mutex = CreateMutex(nullptr, false, nullptr);
if (nullptr != l_mutex)
{
l_instance = new ENetPacketHandler();
if (nullptr == l_instance)
{
l_instance->m_mutexPackets = l_mutex;
}
else
{
mEERROR_S(EERROR_MEMORY);
CloseHandle(l_mutex);
}
}
else
{
mEERROR_SA(EERROR_WINDOWS_ERR, WindowsErrString(GetLastError()));
}
}
return (l_instance);
}
/**
@brief Pop a ENetPacket from the queue. /!\ Mutex.
@return First ENetPacket from the queue.
@return nullptr if queue is empty.
*/
ENetPacket *ENetPacketHandler::popPacket()
{
ENetPacket *l_packet = nullptr;
WaitForSingleObject(m_mutexPackets, INFINITE);
if (false == m_packets.empty())
{
l_packet = m_packets.front();
m_packets.pop();
}
ReleaseMutex(m_mutexPackets);
return (l_packet);
}
/**
@brief Receive a ENetPacket from connected ENetSocket source. /!\ Blocking. /!\ Mutex. /!\ EError.
@details Receive ENetPacketType, then call its ENetPacket...::recv().
@details Can be blocking on bad behavior, waiting for datas that were not properly sent.
@details On success, received ENetPacket is added to queue.
@details Source must be valid.
@param p_src ENetSocket source.
*/
void ENetPacketHandler::recvPacket(ENetSocket *p_src)
{
mEERROR_R();
if (nullptr == p_src)
{
mEERROR_S(EERROR_NULL_PTR);
}
if ((nullptr != p_src)
&& (ENETSOCKET_FLAGS_PROTOCOL_TCP != (p_src->getFlags() & ENETSOCKET_FLAGS_PROTOCOLS)))
{
mEERROR_S(EERROR_NET_SOCKET_PROTOCOL);
}
if (EERROR_NONE == mEERROR)
{
int32 l_len = 0;
ENetPacketType l_type = ENETPACKET_TYPE_DISCONNECT;
l_len = p_src->recv(reinterpret_cast<char*>(&l_type), sizeof(ENetPacketType));
if (EERROR_NONE == mEERROR)
{
if ((sizeof(ENetPacketType) == l_len)
|| (0 == l_len)) // Generate an ENetPacketDisconnect.
{
if (m_generators.find(l_type) != m_generators.end())
{
ENetPacket *l_packet = nullptr;
l_packet = m_generators[l_type](p_src);
if (nullptr != l_packet)
{
l_packet->recv();
if (EERROR_NONE == mEERROR)
{
WaitForSingleObject(m_mutexPackets, INFINITE);
m_packets.push(l_packet);
ReleaseMutex(m_mutexPackets);
}
else
{
mEERROR_SH(EERROR_NET_PACKET_ERR);
}
}
else
{
mEERROR_SH(EERROR_NET_PACKETHANDLER_ERR);
}
}
else
{
mEERROR_S(EERROR_NET_PACKET_TYPE);
}
}
else
{
mEERROR_S(EERROR_NET_PACKET_TRUNCATED);
}
}
else
{
mEERROR_SH(EERROR_NET_SOCKET_ERR);
}
}
}
/**
@brief Read a ENetPacket from buffer. /!\ Mutex. /!\ EError.
@details Read ENetPacketType, then call its ENetPacket...::read().
@details On success, read ENetPacket is added to queue.
@param p_datas Buffer of datas to be read.
@param p_len Length of buffer.
@param p_src ENetSocket source.
*/
void ENetPacketHandler::read(char *p_datas, int32 p_len, ENetSocket *p_src)
{
mEERROR_R();
if (nullptr == p_datas)
{
mEERROR_S(EERROR_NULL_PTR);
}
if (EERROR_NONE == mEERROR)
{
if ((sizeof(ENetPacketType) <= p_len)
|| (0 == p_len)) // Generate an ENetPacketDisconnect.
{
ENetPacketType l_type = ENETPACKET_TYPE_DISCONNECT;
if (0 != p_len)
{
l_type = *reinterpret_cast<ENetPacketType*>(p_datas);
}
if (m_generators.find(l_type) != m_generators.end())
{
ENetPacket *l_packet = nullptr;
l_packet = m_generators[l_type](p_src);
if (nullptr != l_packet)
{
l_packet->read(p_datas + sizeof(ENetPacketType), p_len - sizeof(ENetPacketType));
if (EERROR_NONE == mEERROR)
{
l_packet->setSource(p_src);
WaitForSingleObject(m_mutexPackets, INFINITE);
m_packets.push(l_packet);
ReleaseMutex(m_mutexPackets);
}
else
{
mEERROR_SH(EERROR_NET_PACKET_ERR);
}
}
else
{
mEERROR_SH(EERROR_NET_PACKETHANDLER_ERR);
}
}
else
{
mEERROR_S(EERROR_NET_PACKET_TYPE);
}
}
else
{
mEERROR_S(EERROR_NET_PACKET_TRUNCATED);
}
}
}
/**
@brief Add type/generator to automation. /!\ EError.
@details Type must be over ENETPACKET_TYPE_RESERVED.
@param p_type Type to be added.
@param p_generator Generator for type.
*/
void ENetPacketHandler::setGenerator(ENetPacketType p_type, ENetPacketGenerator p_generator)
{
mEERROR_R();
if (ENETPACKET_TYPE_RESERVED >= p_type)
{
mEERROR_SA(EERROR_NET_PACKET_TYPE, "Trying to add ENetPacketGenerator with reserved ENetPacketType.");
}
if (EERROR_NONE == mEERROR)
{
m_generators[p_type] = p_generator;
}
}
/**
@brief Clean queue from ENetPackets linked to ENetSocket in parameter. /!\ Mutex.
@param p_socket ENetSocket that will cleaned from queue.
*/
void ENetPacketHandler::cleanSocket(const ENetSocket *p_socket)
{
size_t l_size = 0;
WaitForSingleObject(m_mutexPackets, INFINITE);
l_size = m_packets.size();
for (size_t l_pos = 0; l_pos < l_size; ++l_pos)
{
if (*m_packets.front()->getSource() != *p_socket)
{
m_packets.push(m_packets.front());
}
m_packets.pop();
}
ReleaseMutex(m_mutexPackets);
}
}
|
[
"[email protected]"
] | |
519f7f8a6f243b36ab8754a354e72df25052815a
|
14986e2332cbded0a5b438eb25131662ed7fc605
|
/Film_Database/CW2/SingleLanguage.cpp
|
2e3fdecb03fc1fc115c7c7c314d22dd52ea96268
|
[] |
no_license
|
tjoyjoseph/C-_Film_Database_Manipulation
|
e71510d44c20e477c2e4c484840c8777040bd902
|
7323a197991bd8057d7ae4ba3b246328a1a48bc2
|
refs/heads/master
| 2020-03-17T12:10:03.801702 | 2018-05-15T21:51:01 | 2018-05-15T21:51:01 | 133,576,930 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 253 |
cpp
|
#include "SingleLanguage.h"
void SingleLanguage::addLanaguage(string lanaguageType)
{
language = lanaguageType;
}
vector<string> SingleLanguage::getLanguage() const
{
vector<string> tempVector;
tempVector.push_back(language);
return tempVector;
}
|
[
"[email protected]"
] | |
33c9322c4587f7af7c72c2b400ce41f8f19f04ca
|
6da6c9dc6cab546cf50bf72e847c854d70f89205
|
/sender/sender.h
|
62c456d2211b2603d57e88b93638bb3b8c6853e6
|
[
"MIT"
] |
permissive
|
Engin-Boot/environment-case-s1b5
|
97637d44465331af1aa305baf81e43dbfb1dcfed
|
463550045a1c480fd05a4d8a9fefe897e7643f14
|
refs/heads/master
| 2022-12-24T21:17:55.166119 | 2020-09-28T11:34:58 | 2020-09-28T11:34:58 | 293,785,023 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 230 |
h
|
#include<iostream>
#include<string>
#include<vector>
#include<cstring>
#include<fstream>
#include<sstream>
using namespace std;
namespace Sender
{
vector<vector<float>> ParseCSVfile(string );
void print(vector<vector<float>>);
}
|
[
"[email protected]"
] | |
5764f45466266e423a6b8d7a11bb8d2ae0ae4018
|
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
|
/Source Code/server/binaries/chromium/gen/services/content/public/mojom/navigable_contents_factory.mojom-shared-internal.h
|
3b6512d89c4a187591532f65fbc6ca4857de5386
|
[] |
no_license
|
lineCode/wasmview.github.io
|
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
|
eac4c69ea1cf0e9af9da5a500219236470541f9b
|
refs/heads/master
| 2020-09-22T21:05:53.766548 | 2019-08-24T05:34:04 | 2019-08-24T05:34:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,098 |
h
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_CONTENT_PUBLIC_MOJOM_NAVIGABLE_CONTENTS_FACTORY_MOJOM_SHARED_INTERNAL_H_
#define SERVICES_CONTENT_PUBLIC_MOJOM_NAVIGABLE_CONTENTS_FACTORY_MOJOM_SHARED_INTERNAL_H_
#include "mojo/public/cpp/bindings/lib/array_internal.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
#include "mojo/public/cpp/bindings/lib/map_data_internal.h"
#include "mojo/public/cpp/bindings/lib/buffer.h"
#include "services/content/public/mojom/navigable_contents.mojom-shared-internal.h"
#include "ui/gfx/geometry/mojo/geometry.mojom-shared-internal.h"
#include "mojo/public/cpp/bindings/lib/native_enum_data.h"
#include "mojo/public/interfaces/bindings/native_struct.mojom-shared-internal.h"
#include "base/component_export.h"
namespace mojo {
namespace internal {
class ValidationContext;
}
}
namespace content {
namespace mojom {
namespace internal {
class NavigableContentsParams_Data;
#pragma pack(push, 1)
class COMPONENT_EXPORT(CONTENT_SERVICE_MOJOM_SHARED) NavigableContentsParams_Data {
public:
class BufferWriter {
public:
BufferWriter() = default;
void Allocate(mojo::internal::Buffer* serialization_buffer) {
serialization_buffer_ = serialization_buffer;
index_ = serialization_buffer_->Allocate(sizeof(NavigableContentsParams_Data));
new (data()) NavigableContentsParams_Data();
}
bool is_null() const { return !serialization_buffer_; }
NavigableContentsParams_Data* data() {
DCHECK(!is_null());
return serialization_buffer_->Get<NavigableContentsParams_Data>(index_);
}
NavigableContentsParams_Data* operator->() { return data(); }
private:
mojo::internal::Buffer* serialization_buffer_ = nullptr;
size_t index_ = 0;
DISALLOW_COPY_AND_ASSIGN(BufferWriter);
};
static bool Validate(const void* data,
mojo::internal::ValidationContext* validation_context);
mojo::internal::StructHeader header_;
uint8_t enable_view_auto_resize : 1;
uint8_t suppress_navigations : 1;
uint8_t override_background_color : 1;
uint8_t pad2_[3];
uint32_t background_color;
mojo::internal::Pointer<::gfx::mojom::internal::Size_Data> auto_resize_min_size;
mojo::internal::Pointer<::gfx::mojom::internal::Size_Data> auto_resize_max_size;
private:
NavigableContentsParams_Data();
~NavigableContentsParams_Data() = delete;
};
static_assert(sizeof(NavigableContentsParams_Data) == 32,
"Bad sizeof(NavigableContentsParams_Data)");
// Used by NavigableContentsParams::WrapAsMessage to lazily serialize the struct.
template <typename UserType, typename DataView>
struct NavigableContentsParams_UnserializedMessageContext
: public mojo::internal::UnserializedMessageContext {
public:
static const mojo::internal::UnserializedMessageContext::Tag kMessageTag;
NavigableContentsParams_UnserializedMessageContext(
uint32_t message_name,
uint32_t message_flags,
UserType input)
: mojo::internal::UnserializedMessageContext(&kMessageTag, message_name, message_flags)
, user_data_(std::move(input)) {}
~NavigableContentsParams_UnserializedMessageContext() override = default;
UserType TakeData() {
return std::move(user_data_);
}
private:
// mojo::internal::UnserializedMessageContext:
void Serialize(mojo::internal::SerializationContext* context,
mojo::internal::Buffer* buffer) override {
NavigableContentsParams_Data::BufferWriter writer;
mojo::internal::Serialize<DataView>(user_data_, buffer, &writer, context);
}
UserType user_data_;
};
template <typename UserType, typename DataView>
const mojo::internal::UnserializedMessageContext::Tag
NavigableContentsParams_UnserializedMessageContext<UserType, DataView>::kMessageTag = {};
#pragma pack(pop)
} // namespace internal
} // namespace mojom
} // namespace content
#endif // SERVICES_CONTENT_PUBLIC_MOJOM_NAVIGABLE_CONTENTS_FACTORY_MOJOM_SHARED_INTERNAL_H_
|
[
"[email protected]"
] | |
0120e0e72ed514fe85b7243e7f11343594d47321
|
ef68b62f4a1dd2e26e26ef2fc67e18f8fbe96418
|
/cgv/reflect/method_interface_impl.h
|
437531457442a4aee6c36405a6883fd531e4fe66
|
[] |
no_license
|
lintianfang/cleaning_cobotics
|
68d9a4b418cdadab9dde1c24f529f45e7fc3bd4f
|
26ccba618aec0b1176fcfc889e95ed5320ccbe75
|
refs/heads/master
| 2023-02-25T21:36:10.777059 | 2021-01-29T09:49:16 | 2021-01-29T09:49:16 | 281,898,712 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 34,512 |
h
|
#pragma once
#include <cgv/reflect/reflection_handler.h>
namespace cgv {
namespace reflect {
template <typename M>
struct method_interface_impl;
template <typename X, typename R>
struct method_interface_impl<R (X::*)()> : public method_interface
{
typedef R (X::*M)();
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R>
struct method_interface_impl<R (X::*)() const> : public method_interface
{
typedef R (X::*M)() const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
), result_type_name, result_value_ptr);
}
};
template <typename X>
struct method_interface_impl<void (X::*)()> : public method_interface
{
typedef void (X::*M)();
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
);
}
};
template <typename X>
struct method_interface_impl<void (X::*)() const> : public method_interface
{
typedef void (X::*M)() const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
);
}
};
template <typename X, typename R, typename T1>
struct method_interface_impl<R (X::*)(T1)> : public method_interface
{
typedef R (X::*M)(T1);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1>
struct method_interface_impl<R (X::*)(T1) const> : public method_interface
{
typedef R (X::*M)(T1) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1>
struct method_interface_impl<void (X::*)(T1)> : public method_interface
{
typedef void (X::*M)(T1);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0])
);
}
};
template <typename X, typename T1>
struct method_interface_impl<void (X::*)(T1) const> : public method_interface
{
typedef void (X::*M)(T1) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0])
);
}
};
template <typename X, typename R, typename T1, typename T2>
struct method_interface_impl<R (X::*)(T1,T2)> : public method_interface
{
typedef R (X::*M)(T1,T2);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2>
struct method_interface_impl<R (X::*)(T1,T2) const> : public method_interface
{
typedef R (X::*M)(T1,T2) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2>
struct method_interface_impl<void (X::*)(T1,T2)> : public method_interface
{
typedef void (X::*M)(T1,T2);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1])
);
}
};
template <typename X, typename T1, typename T2>
struct method_interface_impl<void (X::*)(T1,T2) const> : public method_interface
{
typedef void (X::*M)(T1,T2) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3>
struct method_interface_impl<R (X::*)(T1,T2,T3)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3>
struct method_interface_impl<R (X::*)(T1,T2,T3) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3>
struct method_interface_impl<void (X::*)(T1,T2,T3)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2])
);
}
};
template <typename X, typename T1, typename T2, typename T3>
struct method_interface_impl<void (X::*)(T1,T2,T3) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3])
);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4])
);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5])
);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6,T7)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6,T7);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6,T7) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6,T7) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6,T7)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6,T7);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6])
);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6,T7) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6,T7) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6])
);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6,T7,T8)> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6,T7,T8);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6]),
cgv::type::variant<T8>::get(param_type_names[7],param_value_ptrs[7])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
struct method_interface_impl<R (X::*)(T1,T2,T3,T4,T5,T6,T7,T8) const> : public method_interface
{
typedef R (X::*M)(T1,T2,T3,T4,T5,T6,T7,T8) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
cgv::type::set_variant((((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6]),
cgv::type::variant<T8>::get(param_type_names[7],param_value_ptrs[7])
), result_type_name, result_value_ptr);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6,T7,T8)> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6,T7,T8);
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6]),
cgv::type::variant<T8>::get(param_type_names[7],param_value_ptrs[7])
);
}
};
template <typename X, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
struct method_interface_impl<void (X::*)(T1,T2,T3,T4,T5,T6,T7,T8) const> : public method_interface
{
typedef void (X::*M)(T1,T2,T3,T4,T5,T6,T7,T8) const;
M m;
method_interface_impl(M _m) : m(_m) {}
void call_void(void* instance,
const std::vector<abst_reflection_traits*>& param_value_traits,
const std::vector<const void*>& param_value_ptrs,
const std::vector<std::string>& param_type_names,
const abst_reflection_traits* result_traits,
void* result_value_ptr,
const std::string& result_type_name)
{
(((X*)instance)->*m)(
cgv::type::variant<T1>::get(param_type_names[0],param_value_ptrs[0]),
cgv::type::variant<T2>::get(param_type_names[1],param_value_ptrs[1]),
cgv::type::variant<T3>::get(param_type_names[2],param_value_ptrs[2]),
cgv::type::variant<T4>::get(param_type_names[3],param_value_ptrs[3]),
cgv::type::variant<T5>::get(param_type_names[4],param_value_ptrs[4]),
cgv::type::variant<T6>::get(param_type_names[5],param_value_ptrs[5]),
cgv::type::variant<T7>::get(param_type_names[6],param_value_ptrs[6]),
cgv::type::variant<T8>::get(param_type_names[7],param_value_ptrs[7])
);
}
};
}
}
|
[
"[email protected]"
] | |
cd54f985fab5bc39cb5be25106798aa8cdd95351
|
f34e03c61a0498de158bd73f79ff7f7281a0ddf4
|
/src/controller/java/gen/CHIPClusters-JNI.cpp
|
9bbb53d0dcdbfc64c09a0223a68d978efbd8ccd1
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
eoebakke-grundfos/connectedhomeip
|
8dce9b884da2bdf5ce7c60a928c6009011cb2769
|
17dbc199973f3532d360d26ecbe4f13a4ecafebc
|
refs/heads/master
| 2023-06-13T08:59:27.615613 | 2021-06-26T06:47:57 | 2021-06-26T06:47:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 450,812 |
cpp
|
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// THIS FILE IS GENERATED BY ZAP
#include "gen/CHIPClientCallbacks.h"
#include "gen/CHIPClusters.h"
#include <controller/java/CHIPJNIError.h>
#include <controller/java/JniReferences.h>
#include <controller/java/JniTypeWrappers.h>
#include <controller/java/StackLock.h>
#include <core/CHIPSafeCasts.h>
#include <jni.h>
#include <lib/support/Span.h>
#include <support/CodeUtils.h>
#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \
extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME
using namespace chip;
using namespace chip::Controller;
static CHIP_ERROR CreateChipClusterException(JNIEnv * env, jint errorCode, jthrowable & outEx);
static CHIP_ERROR CreateIllegalStateException(JNIEnv * env, const char message[], jint errorCode, jthrowable & outEx);
CHIP_ERROR CreateChipClusterException(JNIEnv * env, jint errorCode, jthrowable & outEx)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID exceptionConstructor;
jclass clusterExceptionCls;
err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/ChipClusterException", clusterExceptionCls);
VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
exceptionConstructor = env->GetMethodID(clusterExceptionCls, "<init>", "(I)V");
VerifyOrReturnError(exceptionConstructor != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
outEx = (jthrowable) env->NewObject(clusterExceptionCls, exceptionConstructor, errorCode);
VerifyOrReturnError(outEx != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
return err;
}
CHIP_ERROR CreateIllegalStateException(JNIEnv * env, const char message[], jint errorCode, jthrowable & outEx)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID exceptionConstructor;
jclass exceptionClass;
jstring errStr;
err = JniReferences::GetInstance().GetClassRef(env, "java/lang/IllegalStateException", exceptionClass);
SuccessOrExit(err);
exceptionConstructor = env->GetMethodID(exceptionClass, "<init>", "(Ljava/lang/String;)V");
VerifyOrExit(exceptionConstructor != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND);
char buf[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE];
snprintf(buf, sizeof(buf), "%s: %d", message, errorCode);
errStr = env->NewStringUTF(buf);
outEx = (jthrowable) env->NewObject(exceptionClass, exceptionConstructor, errStr);
VerifyOrExit(outEx != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND);
exit:
env->DeleteGlobalRef(exceptionClass);
return err;
}
class CHIPDefaultSuccessCallback : public Callback::Callback<DefaultSuccessCallback>
{
public:
CHIPDefaultSuccessCallback(jobject javaCallback) : Callback::Callback<DefaultSuccessCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDefaultSuccessCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID javaMethod;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
CHIPDefaultSuccessCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDefaultSuccessCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
// It's valid for javaCallbackRef to be nullptr if the Java code passed in a null callback.
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->ExceptionClear();
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDefaultFailureCallback : public Callback::Callback<DefaultFailureCallback>
{
public:
CHIPDefaultFailureCallback(jobject javaCallback) : Callback::Callback<DefaultFailureCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDefaultFailureCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t status)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID javaMethod;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jthrowable exception;
CHIPDefaultFailureCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDefaultFailureCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
// It's valid for javaCallbackRef to be nullptr if the Java code passed in a null callback.
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onError", "(Ljava/lang/Exception;)V", &javaMethod);
SuccessOrExit(err);
err = CreateChipClusterException(env, status, exception);
SuccessOrExit(err);
env->ExceptionClear();
env->CallVoidMethod(javaCallbackRef, javaMethod, exception);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
// TODO(#7376): add attribute callbacks.
class CHIPAccountLoginClusterGetSetupPINResponseCallback : public Callback::Callback<AccountLoginClusterGetSetupPINResponseCallback>
{
public:
CHIPAccountLoginClusterGetSetupPINResponseCallback(jobject javaCallback) :
Callback::Callback<AccountLoginClusterGetSetupPINResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPAccountLoginClusterGetSetupPINResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t * setupPIN)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPAccountLoginClusterGetSetupPINResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString setupPINStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPAccountLoginClusterGetSetupPINResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, setupPINStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPApplicationLauncherClusterLaunchAppResponseCallback
: public Callback::Callback<ApplicationLauncherClusterLaunchAppResponseCallback>
{
public:
CHIPApplicationLauncherClusterLaunchAppResponseCallback(jobject javaCallback) :
Callback::Callback<ApplicationLauncherClusterLaunchAppResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPApplicationLauncherClusterLaunchAppResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t * data)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPApplicationLauncherClusterLaunchAppResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString dataStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPApplicationLauncherClusterLaunchAppResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, dataStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPContentLauncherClusterLaunchContentResponseCallback
: public Callback::Callback<ContentLauncherClusterLaunchContentResponseCallback>
{
public:
CHIPContentLauncherClusterLaunchContentResponseCallback(jobject javaCallback) :
Callback::Callback<ContentLauncherClusterLaunchContentResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPContentLauncherClusterLaunchContentResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t * data, uint8_t contentLaunchStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPContentLauncherClusterLaunchContentResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString dataStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPContentLauncherClusterLaunchContentResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, dataStr.jniValue(), static_cast<jint>(contentLaunchStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPContentLauncherClusterLaunchURLResponseCallback
: public Callback::Callback<ContentLauncherClusterLaunchURLResponseCallback>
{
public:
CHIPContentLauncherClusterLaunchURLResponseCallback(jobject javaCallback) :
Callback::Callback<ContentLauncherClusterLaunchURLResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPContentLauncherClusterLaunchURLResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t * data, uint8_t contentLaunchStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPContentLauncherClusterLaunchURLResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString dataStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPContentLauncherClusterLaunchURLResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, dataStr.jniValue(), static_cast<jint>(contentLaunchStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearAllPinsResponseCallback : public Callback::Callback<DoorLockClusterClearAllPinsResponseCallback>
{
public:
CHIPDoorLockClusterClearAllPinsResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearAllPinsResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearAllPinsResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearAllPinsResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearAllPinsResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearAllRfidsResponseCallback : public Callback::Callback<DoorLockClusterClearAllRfidsResponseCallback>
{
public:
CHIPDoorLockClusterClearAllRfidsResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearAllRfidsResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearAllRfidsResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearAllRfidsResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearAllRfidsResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearHolidayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterClearHolidayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterClearHolidayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearHolidayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearHolidayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearHolidayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearHolidayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearPinResponseCallback : public Callback::Callback<DoorLockClusterClearPinResponseCallback>
{
public:
CHIPDoorLockClusterClearPinResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearPinResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearPinResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearPinResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearPinResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearRfidResponseCallback : public Callback::Callback<DoorLockClusterClearRfidResponseCallback>
{
public:
CHIPDoorLockClusterClearRfidResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearRfidResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearRfidResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearRfidResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearRfidResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearWeekdayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterClearWeekdayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterClearWeekdayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearWeekdayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearWeekdayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearWeekdayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearWeekdayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterClearYeardayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterClearYeardayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterClearYeardayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterClearYeardayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterClearYeardayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterClearYeardayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterClearYeardayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetHolidayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterGetHolidayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterGetHolidayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetHolidayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetHolidayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t scheduleId, uint32_t localStartTime, uint32_t localEndTime,
uint8_t operatingModeDuringHoliday)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetHolidayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetHolidayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IJJI)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(scheduleId), static_cast<jlong>(localStartTime),
static_cast<jlong>(localEndTime), static_cast<jint>(operatingModeDuringHoliday));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetLogRecordResponseCallback : public Callback::Callback<DoorLockClusterGetLogRecordResponseCallback>
{
public:
CHIPDoorLockClusterGetLogRecordResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetLogRecordResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetLogRecordResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t logEntryId, uint32_t timestamp, uint8_t eventType, uint8_t source,
uint8_t eventIdOrAlarmCode, uint16_t userId, uint8_t * pin)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetLogRecordResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString pinStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetLogRecordResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err =
JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IJIIIILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(logEntryId), static_cast<jlong>(timestamp),
static_cast<jint>(eventType), static_cast<jint>(source), static_cast<jint>(eventIdOrAlarmCode),
static_cast<jint>(userId), pinStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetPinResponseCallback : public Callback::Callback<DoorLockClusterGetPinResponseCallback>
{
public:
CHIPDoorLockClusterGetPinResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetPinResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetPinResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t userId, uint8_t userStatus, uint8_t userType, uint8_t * pin)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetPinResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString pinStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetPinResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IIILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(userId), static_cast<jint>(userStatus),
static_cast<jint>(userType), pinStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetRfidResponseCallback : public Callback::Callback<DoorLockClusterGetRfidResponseCallback>
{
public:
CHIPDoorLockClusterGetRfidResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetRfidResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetRfidResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t userId, uint8_t userStatus, uint8_t userType, uint8_t * rfid)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetRfidResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString rfidStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetRfidResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IIILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(userId), static_cast<jint>(userStatus),
static_cast<jint>(userType), rfidStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetUserTypeResponseCallback : public Callback::Callback<DoorLockClusterGetUserTypeResponseCallback>
{
public:
CHIPDoorLockClusterGetUserTypeResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetUserTypeResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetUserTypeResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t userId, uint8_t userType)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetUserTypeResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetUserTypeResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(II)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(userId), static_cast<jint>(userType));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetWeekdayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterGetWeekdayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterGetWeekdayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetWeekdayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetWeekdayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t scheduleId, uint16_t userId, uint8_t daysMask, uint8_t startHour,
uint8_t startMinute, uint8_t endHour, uint8_t endMinute)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetWeekdayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetWeekdayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IIIIIII)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(scheduleId), static_cast<jint>(userId),
static_cast<jint>(daysMask), static_cast<jint>(startHour), static_cast<jint>(startMinute),
static_cast<jint>(endHour), static_cast<jint>(endMinute));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterGetYeardayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterGetYeardayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterGetYeardayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterGetYeardayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterGetYeardayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t scheduleId, uint16_t userId, uint32_t localStartTime, uint32_t localEndTime)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterGetYeardayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterGetYeardayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IIJJ)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(scheduleId), static_cast<jint>(userId),
static_cast<jlong>(localStartTime), static_cast<jlong>(localEndTime));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterLockDoorResponseCallback : public Callback::Callback<DoorLockClusterLockDoorResponseCallback>
{
public:
CHIPDoorLockClusterLockDoorResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterLockDoorResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterLockDoorResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterLockDoorResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterLockDoorResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetHolidayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterSetHolidayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterSetHolidayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetHolidayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetHolidayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetHolidayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetHolidayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetPinResponseCallback : public Callback::Callback<DoorLockClusterSetPinResponseCallback>
{
public:
CHIPDoorLockClusterSetPinResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetPinResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetPinResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetPinResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetPinResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetRfidResponseCallback : public Callback::Callback<DoorLockClusterSetRfidResponseCallback>
{
public:
CHIPDoorLockClusterSetRfidResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetRfidResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetRfidResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetRfidResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetRfidResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetUserTypeResponseCallback : public Callback::Callback<DoorLockClusterSetUserTypeResponseCallback>
{
public:
CHIPDoorLockClusterSetUserTypeResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetUserTypeResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetUserTypeResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetUserTypeResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetUserTypeResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetWeekdayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterSetWeekdayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterSetWeekdayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetWeekdayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetWeekdayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetWeekdayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetWeekdayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterSetYeardayScheduleResponseCallback
: public Callback::Callback<DoorLockClusterSetYeardayScheduleResponseCallback>
{
public:
CHIPDoorLockClusterSetYeardayScheduleResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterSetYeardayScheduleResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterSetYeardayScheduleResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterSetYeardayScheduleResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterSetYeardayScheduleResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterUnlockDoorResponseCallback : public Callback::Callback<DoorLockClusterUnlockDoorResponseCallback>
{
public:
CHIPDoorLockClusterUnlockDoorResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterUnlockDoorResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterUnlockDoorResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterUnlockDoorResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterUnlockDoorResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPDoorLockClusterUnlockWithTimeoutResponseCallback
: public Callback::Callback<DoorLockClusterUnlockWithTimeoutResponseCallback>
{
public:
CHIPDoorLockClusterUnlockWithTimeoutResponseCallback(jobject javaCallback) :
Callback::Callback<DoorLockClusterUnlockWithTimeoutResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPDoorLockClusterUnlockWithTimeoutResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPDoorLockClusterUnlockWithTimeoutResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPDoorLockClusterUnlockWithTimeoutResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGeneralCommissioningClusterArmFailSafeResponseCallback
: public Callback::Callback<GeneralCommissioningClusterArmFailSafeResponseCallback>
{
public:
CHIPGeneralCommissioningClusterArmFailSafeResponseCallback(jobject javaCallback) :
Callback::Callback<GeneralCommissioningClusterArmFailSafeResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGeneralCommissioningClusterArmFailSafeResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGeneralCommissioningClusterArmFailSafeResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGeneralCommissioningClusterArmFailSafeResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback
: public Callback::Callback<GeneralCommissioningClusterCommissioningCompleteResponseCallback>
{
public:
CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback(jobject javaCallback) :
Callback::Callback<GeneralCommissioningClusterCommissioningCompleteResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback
: public Callback::Callback<GeneralCommissioningClusterSetRegulatoryConfigResponseCallback>
{
public:
CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback(jobject javaCallback) :
Callback::Callback<GeneralCommissioningClusterSetRegulatoryConfigResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGroupsClusterAddGroupResponseCallback : public Callback::Callback<GroupsClusterAddGroupResponseCallback>
{
public:
CHIPGroupsClusterAddGroupResponseCallback(jobject javaCallback) :
Callback::Callback<GroupsClusterAddGroupResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGroupsClusterAddGroupResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGroupsClusterAddGroupResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGroupsClusterAddGroupResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGroupsClusterGetGroupMembershipResponseCallback
: public Callback::Callback<GroupsClusterGetGroupMembershipResponseCallback>
{
public:
CHIPGroupsClusterGetGroupMembershipResponseCallback(jobject javaCallback) :
Callback::Callback<GroupsClusterGetGroupMembershipResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGroupsClusterGetGroupMembershipResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t capacity, uint8_t groupCount,
/* TYPE WARNING: array array defaults to */ uint8_t * groupList)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGroupsClusterGetGroupMembershipResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGroupsClusterGetGroupMembershipResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(II)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(capacity), static_cast<jint>(groupCount)
// groupList: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGroupsClusterRemoveGroupResponseCallback : public Callback::Callback<GroupsClusterRemoveGroupResponseCallback>
{
public:
CHIPGroupsClusterRemoveGroupResponseCallback(jobject javaCallback) :
Callback::Callback<GroupsClusterRemoveGroupResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGroupsClusterRemoveGroupResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGroupsClusterRemoveGroupResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGroupsClusterRemoveGroupResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPGroupsClusterViewGroupResponseCallback : public Callback::Callback<GroupsClusterViewGroupResponseCallback>
{
public:
CHIPGroupsClusterViewGroupResponseCallback(jobject javaCallback) :
Callback::Callback<GroupsClusterViewGroupResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPGroupsClusterViewGroupResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId, uint8_t * groupName)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPGroupsClusterViewGroupResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString groupNameStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPGroupsClusterViewGroupResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId), groupNameStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPIdentifyClusterIdentifyQueryResponseCallback : public Callback::Callback<IdentifyClusterIdentifyQueryResponseCallback>
{
public:
CHIPIdentifyClusterIdentifyQueryResponseCallback(jobject javaCallback) :
Callback::Callback<IdentifyClusterIdentifyQueryResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPIdentifyClusterIdentifyQueryResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t timeout)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPIdentifyClusterIdentifyQueryResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPIdentifyClusterIdentifyQueryResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(timeout));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPKeypadInputClusterSendKeyResponseCallback : public Callback::Callback<KeypadInputClusterSendKeyResponseCallback>
{
public:
CHIPKeypadInputClusterSendKeyResponseCallback(jobject javaCallback) :
Callback::Callback<KeypadInputClusterSendKeyResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPKeypadInputClusterSendKeyResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPKeypadInputClusterSendKeyResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPKeypadInputClusterSendKeyResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "()V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaFastForwardResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaFastForwardResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaFastForwardResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaFastForwardResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaFastForwardResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaFastForwardResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaFastForwardResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaNextResponseCallback : public Callback::Callback<MediaPlaybackClusterMediaNextResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaNextResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaNextResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaNextResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaNextResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaNextResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaPauseResponseCallback : public Callback::Callback<MediaPlaybackClusterMediaPauseResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaPauseResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaPauseResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaPauseResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaPauseResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaPauseResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaPlayResponseCallback : public Callback::Callback<MediaPlaybackClusterMediaPlayResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaPlayResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaPlayResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaPlayResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaPlayResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaPlayResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaPreviousResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaPreviousResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaPreviousResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaPreviousResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaPreviousResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaPreviousResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaPreviousResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaRewindResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaRewindResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaRewindResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaRewindResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaRewindResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaRewindResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaRewindResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaSkipBackwardResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaSkipBackwardResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaSkipForwardResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaSkipForwardResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaSkipSeekResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaSkipSeekResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaStartOverResponseCallback
: public Callback::Callback<MediaPlaybackClusterMediaStartOverResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaStartOverResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaStartOverResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaStartOverResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaStartOverResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaStartOverResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPMediaPlaybackClusterMediaStopResponseCallback : public Callback::Callback<MediaPlaybackClusterMediaStopResponseCallback>
{
public:
CHIPMediaPlaybackClusterMediaStopResponseCallback(jobject javaCallback) :
Callback::Callback<MediaPlaybackClusterMediaStopResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPMediaPlaybackClusterMediaStopResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t mediaPlaybackStatus)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPMediaPlaybackClusterMediaStopResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPMediaPlaybackClusterMediaStopResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(mediaPlaybackStatus));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterAddThreadNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterAddThreadNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterAddWiFiNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterAddWiFiNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterDisableNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterDisableNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterDisableNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterDisableNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterDisableNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterDisableNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterDisableNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterEnableNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterEnableNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterEnableNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterEnableNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterEnableNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterEnableNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterEnableNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterRemoveNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterRemoveNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterScanNetworksResponseCallback
: public Callback::Callback<NetworkCommissioningClusterScanNetworksResponseCallback>
{
public:
CHIPNetworkCommissioningClusterScanNetworksResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterScanNetworksResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterScanNetworksResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText,
/* TYPE WARNING: array array defaults to */ uint8_t * wifiScanResults,
/* TYPE WARNING: array array defaults to */ uint8_t * threadScanResults)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterScanNetworksResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterScanNetworksResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue()
// wifiScanResults: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
// threadScanResults: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterUpdateThreadNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterUpdateThreadNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback
: public Callback::Callback<NetworkCommissioningClusterUpdateWiFiNetworkResponseCallback>
{
public:
CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback(jobject javaCallback) :
Callback::Callback<NetworkCommissioningClusterUpdateWiFiNetworkResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t errorCode, uint8_t * debugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString debugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(ILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(errorCode), debugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback
: public Callback::Callback<OtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback>
{
public:
CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback(jobject javaCallback) :
Callback::Callback<OtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t action, uint32_t delayedActionTime)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IJ)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(action), static_cast<jlong>(delayedActionTime));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback
: public Callback::Callback<OtaSoftwareUpdateServerClusterQueryImageResponseCallback>
{
public:
CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback(jobject javaCallback) :
Callback::Callback<OtaSoftwareUpdateServerClusterQueryImageResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint32_t delayedActionTime, uint8_t * imageURI, uint32_t softwareVersion,
chip::ByteSpan updateToken, uint8_t userConsentNeeded, chip::ByteSpan metadataForClient)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString imageURIStr(env, "");
jbyteArray updateTokenArr;
jbyteArray metadataForClientArr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err =
JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(JLjava/lang/String;J[BI[B)V", &javaMethod);
SuccessOrExit(err);
updateTokenArr = env->NewByteArray(updateToken.size());
VerifyOrExit(updateTokenArr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(updateTokenArr, 0, updateToken.size(), reinterpret_cast<const jbyte *>(updateToken.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
metadataForClientArr = env->NewByteArray(metadataForClient.size());
VerifyOrExit(metadataForClientArr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(metadataForClientArr, 0, metadataForClient.size(),
reinterpret_cast<const jbyte *>(metadataForClient.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jlong>(delayedActionTime), imageURIStr.jniValue(),
static_cast<jlong>(softwareVersion), updateTokenArr, static_cast<jint>(userConsentNeeded),
metadataForClientArr);
env->DeleteLocalRef(updateTokenArr);
env->DeleteLocalRef(metadataForClientArr);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPOperationalCredentialsClusterOpCSRResponseCallback
: public Callback::Callback<OperationalCredentialsClusterOpCSRResponseCallback>
{
public:
CHIPOperationalCredentialsClusterOpCSRResponseCallback(jobject javaCallback) :
Callback::Callback<OperationalCredentialsClusterOpCSRResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPOperationalCredentialsClusterOpCSRResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, chip::ByteSpan CSR, chip::ByteSpan CSRNonce, chip::ByteSpan VendorReserved1,
chip::ByteSpan VendorReserved2, chip::ByteSpan VendorReserved3, chip::ByteSpan Signature)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPOperationalCredentialsClusterOpCSRResponseCallback * cppCallback = nullptr;
jbyteArray CSRArr;
jbyteArray CSRNonceArr;
jbyteArray VendorReserved1Arr;
jbyteArray VendorReserved2Arr;
jbyteArray VendorReserved3Arr;
jbyteArray SignatureArr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPOperationalCredentialsClusterOpCSRResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "([B[B[B[B[B[B)V", &javaMethod);
SuccessOrExit(err);
CSRArr = env->NewByteArray(CSR.size());
VerifyOrExit(CSRArr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(CSRArr, 0, CSR.size(), reinterpret_cast<const jbyte *>(CSR.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
CSRNonceArr = env->NewByteArray(CSRNonce.size());
VerifyOrExit(CSRNonceArr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(CSRNonceArr, 0, CSRNonce.size(), reinterpret_cast<const jbyte *>(CSRNonce.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
VendorReserved1Arr = env->NewByteArray(VendorReserved1.size());
VerifyOrExit(VendorReserved1Arr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(VendorReserved1Arr, 0, VendorReserved1.size(),
reinterpret_cast<const jbyte *>(VendorReserved1.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
VendorReserved2Arr = env->NewByteArray(VendorReserved2.size());
VerifyOrExit(VendorReserved2Arr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(VendorReserved2Arr, 0, VendorReserved2.size(),
reinterpret_cast<const jbyte *>(VendorReserved2.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
VendorReserved3Arr = env->NewByteArray(VendorReserved3.size());
VerifyOrExit(VendorReserved3Arr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(VendorReserved3Arr, 0, VendorReserved3.size(),
reinterpret_cast<const jbyte *>(VendorReserved3.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
SignatureArr = env->NewByteArray(Signature.size());
VerifyOrExit(SignatureArr != nullptr, err = CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(SignatureArr, 0, Signature.size(), reinterpret_cast<const jbyte *>(Signature.data()));
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
env->CallVoidMethod(javaCallbackRef, javaMethod, CSRArr, CSRNonceArr, VendorReserved1Arr, VendorReserved2Arr,
VendorReserved3Arr, SignatureArr);
env->DeleteLocalRef(CSRArr);
env->DeleteLocalRef(CSRNonceArr);
env->DeleteLocalRef(VendorReserved1Arr);
env->DeleteLocalRef(VendorReserved2Arr);
env->DeleteLocalRef(VendorReserved3Arr);
env->DeleteLocalRef(SignatureArr);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPOperationalCredentialsClusterOpCertResponseCallback
: public Callback::Callback<OperationalCredentialsClusterOpCertResponseCallback>
{
public:
CHIPOperationalCredentialsClusterOpCertResponseCallback(jobject javaCallback) :
Callback::Callback<OperationalCredentialsClusterOpCertResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPOperationalCredentialsClusterOpCertResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t StatusCode, uint64_t FabricIndex, uint8_t * DebugText)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPOperationalCredentialsClusterOpCertResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString DebugTextStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPOperationalCredentialsClusterOpCertResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IJLjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(StatusCode), static_cast<jlong>(FabricIndex),
DebugTextStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPOperationalCredentialsClusterSetFabricResponseCallback
: public Callback::Callback<OperationalCredentialsClusterSetFabricResponseCallback>
{
public:
CHIPOperationalCredentialsClusterSetFabricResponseCallback(jobject javaCallback) :
Callback::Callback<OperationalCredentialsClusterSetFabricResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPOperationalCredentialsClusterSetFabricResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, chip::FabricId FabricId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPOperationalCredentialsClusterSetFabricResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPOperationalCredentialsClusterSetFabricResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(J)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jlong>(FabricId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterAddSceneResponseCallback : public Callback::Callback<ScenesClusterAddSceneResponseCallback>
{
public:
CHIPScenesClusterAddSceneResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterAddSceneResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterAddSceneResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId, uint8_t sceneId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterAddSceneResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterAddSceneResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(II)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId), static_cast<jint>(sceneId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterGetSceneMembershipResponseCallback
: public Callback::Callback<ScenesClusterGetSceneMembershipResponseCallback>
{
public:
CHIPScenesClusterGetSceneMembershipResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterGetSceneMembershipResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterGetSceneMembershipResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t capacity, uint16_t groupId, uint8_t sceneCount,
/* TYPE WARNING: array array defaults to */ uint8_t * sceneList)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterGetSceneMembershipResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterGetSceneMembershipResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(III)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(capacity), static_cast<jint>(groupId),
static_cast<jint>(sceneCount)
// sceneList: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterRemoveAllScenesResponseCallback : public Callback::Callback<ScenesClusterRemoveAllScenesResponseCallback>
{
public:
CHIPScenesClusterRemoveAllScenesResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterRemoveAllScenesResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterRemoveAllScenesResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterRemoveAllScenesResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterRemoveAllScenesResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterRemoveSceneResponseCallback : public Callback::Callback<ScenesClusterRemoveSceneResponseCallback>
{
public:
CHIPScenesClusterRemoveSceneResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterRemoveSceneResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterRemoveSceneResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId, uint8_t sceneId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterRemoveSceneResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterRemoveSceneResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(II)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId), static_cast<jint>(sceneId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterStoreSceneResponseCallback : public Callback::Callback<ScenesClusterStoreSceneResponseCallback>
{
public:
CHIPScenesClusterStoreSceneResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterStoreSceneResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterStoreSceneResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId, uint8_t sceneId)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterStoreSceneResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterStoreSceneResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(II)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId), static_cast<jint>(sceneId));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPScenesClusterViewSceneResponseCallback : public Callback::Callback<ScenesClusterViewSceneResponseCallback>
{
public:
CHIPScenesClusterViewSceneResponseCallback(jobject javaCallback) :
Callback::Callback<ScenesClusterViewSceneResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPScenesClusterViewSceneResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint16_t groupId, uint8_t sceneId, uint16_t transitionTime, uint8_t * sceneName,
/* TYPE WARNING: array array defaults to */ uint8_t * extensionFieldSets)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPScenesClusterViewSceneResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString sceneNameStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPScenesClusterViewSceneResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(IIILjava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(groupId), static_cast<jint>(sceneId),
static_cast<jint>(transitionTime), sceneNameStr.jniValue()
// extensionFieldSets: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPTvChannelClusterChangeChannelResponseCallback : public Callback::Callback<TvChannelClusterChangeChannelResponseCallback>
{
public:
CHIPTvChannelClusterChangeChannelResponseCallback(jobject javaCallback) :
Callback::Callback<TvChannelClusterChangeChannelResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPTvChannelClusterChangeChannelResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, /* TYPE WARNING: array array defaults to */ uint8_t * ChannelMatch, uint8_t ErrorType)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPTvChannelClusterChangeChannelResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPTvChannelClusterChangeChannelResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef,
javaMethod
// ChannelMatch: /* TYPE WARNING: array array defaults to */ uint8_t *
// Conversion from this type to Java is not properly implemented yet
,
static_cast<jint>(ErrorType));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPTargetNavigatorClusterNavigateTargetResponseCallback
: public Callback::Callback<TargetNavigatorClusterNavigateTargetResponseCallback>
{
public:
CHIPTargetNavigatorClusterNavigateTargetResponseCallback(jobject javaCallback) :
Callback::Callback<TargetNavigatorClusterNavigateTargetResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPTargetNavigatorClusterNavigateTargetResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t * data)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPTargetNavigatorClusterNavigateTargetResponseCallback * cppCallback = nullptr;
// ByteSpan is not properly returned yet, temporarily use empty string
UtfString dataStr(env, "");
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPTargetNavigatorClusterNavigateTargetResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, dataStr.jniValue());
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
class CHIPTestClusterClusterTestSpecificResponseCallback : public Callback::Callback<TestClusterClusterTestSpecificResponseCallback>
{
public:
CHIPTestClusterClusterTestSpecificResponseCallback(jobject javaCallback) :
Callback::Callback<TestClusterClusterTestSpecificResponseCallback>(CallbackFn, this)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
javaCallbackRef = env->NewGlobalRef(javaCallback);
if (javaCallbackRef == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
}
}
~CHIPTestClusterClusterTestSpecificResponseCallback()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env == nullptr)
{
ChipLogError(Zcl, "Could not create global reference for Java callback");
return;
}
env->DeleteGlobalRef(javaCallbackRef);
};
static void CallbackFn(void * context, uint8_t returnValue)
{
StackUnlockGuard unlockGuard(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jobject javaCallbackRef;
jmethodID javaMethod;
CHIPTestClusterClusterTestSpecificResponseCallback * cppCallback = nullptr;
VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV);
cppCallback = reinterpret_cast<CHIPTestClusterClusterTestSpecificResponseCallback *>(context);
VerifyOrExit(cppCallback != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT);
javaCallbackRef = cppCallback->javaCallbackRef;
VerifyOrExit(javaCallbackRef != nullptr, err = CHIP_NO_ERROR);
err = JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod);
SuccessOrExit(err);
env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<jint>(returnValue));
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error invoking Java callback: %d", err);
}
if (cppCallback != nullptr)
{
cppCallback->Cancel();
delete cppCallback;
}
}
private:
jobject javaCallbackRef;
};
JNI_METHOD(void, BaseChipCluster, deleteCluster)(JNIEnv * env, jobject self, jlong clusterPtr)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ClusterBase * cluster = reinterpret_cast<ClusterBase *>(clusterPtr);
if (cluster != nullptr)
{
delete cluster;
}
}
JNI_METHOD(jlong, AccountLoginCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
AccountLoginCluster * cppCluster = new AccountLoginCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, AccountLoginCluster, getSetupPIN)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring tempAccountIdentifier)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
AccountLoginCluster * cppCluster;
JniUtfString tempAccountIdentifierStr(env, tempAccountIdentifier);
CHIPAccountLoginClusterGetSetupPINResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<AccountLoginCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPAccountLoginClusterGetSetupPINResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err =
cppCluster->GetSetupPIN(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) tempAccountIdentifier, strlen(tempAccountIdentifierStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, AccountLoginCluster, login)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring tempAccountIdentifier, jstring setupPIN)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
AccountLoginCluster * cppCluster;
JniUtfString tempAccountIdentifierStr(env, tempAccountIdentifier);
JniUtfString setupPINStr(env, setupPIN);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<AccountLoginCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Login(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) tempAccountIdentifier, strlen(tempAccountIdentifierStr.c_str())),
chip::ByteSpan((const uint8_t *) setupPIN, strlen(setupPINStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, ApplicationBasicCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ApplicationBasicCluster * cppCluster = new ApplicationBasicCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ApplicationBasicCluster, changeStatus)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint status)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ApplicationBasicCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ApplicationBasicCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ChangeStatus(onSuccess->Cancel(), onFailure->Cancel(), status);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, ApplicationLauncherCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ApplicationLauncherCluster * cppCluster = new ApplicationLauncherCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ApplicationLauncherCluster, launchApp)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring data, jint catalogVendorId, jstring applicationId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ApplicationLauncherCluster * cppCluster;
JniUtfString dataStr(env, data);
JniUtfString applicationIdStr(env, applicationId);
CHIPApplicationLauncherClusterLaunchAppResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ApplicationLauncherCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPApplicationLauncherClusterLaunchAppResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->LaunchApp(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) data, strlen(dataStr.c_str())), catalogVendorId,
chip::ByteSpan((const uint8_t *) applicationId, strlen(applicationIdStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, AudioOutputCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
AudioOutputCluster * cppCluster = new AudioOutputCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, AudioOutputCluster, renameOutput)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint index, jstring name)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
AudioOutputCluster * cppCluster;
JniUtfString nameStr(env, name);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<AudioOutputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RenameOutput(onSuccess->Cancel(), onFailure->Cancel(), index,
chip::ByteSpan((const uint8_t *) name, strlen(nameStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, AudioOutputCluster, selectOutput)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint index)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
AudioOutputCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<AudioOutputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SelectOutput(onSuccess->Cancel(), onFailure->Cancel(), index);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, BarrierControlCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
BarrierControlCluster * cppCluster = new BarrierControlCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, BarrierControlCluster, barrierControlGoToPercent)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint percentOpen)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
BarrierControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<BarrierControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->BarrierControlGoToPercent(onSuccess->Cancel(), onFailure->Cancel(), percentOpen);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, BarrierControlCluster, barrierControlStop)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
BarrierControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<BarrierControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->BarrierControlStop(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, BasicCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
BasicCluster * cppCluster = new BasicCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, BasicCluster, mfgSpecificPing)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
BasicCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<BasicCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MfgSpecificPing(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, BinaryInputBasicCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
BinaryInputBasicCluster * cppCluster = new BinaryInputBasicCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, BindingCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
BindingCluster * cppCluster = new BindingCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, BindingCluster, bind)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong nodeId, jint groupId, jint endpointId, jint clusterId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
BindingCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<BindingCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Bind(onSuccess->Cancel(), onFailure->Cancel(), nodeId, groupId, endpointId, clusterId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, BindingCluster, unbind)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong nodeId, jint groupId, jint endpointId, jint clusterId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
BindingCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<BindingCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Unbind(onSuccess->Cancel(), onFailure->Cancel(), nodeId, groupId, endpointId, clusterId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, BridgedDeviceBasicCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
BridgedDeviceBasicCluster * cppCluster = new BridgedDeviceBasicCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, ColorControlCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ColorControlCluster * cppCluster = new ColorControlCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ColorControlCluster, moveColor)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint rateX, jint rateY, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveColor(onSuccess->Cancel(), onFailure->Cancel(), rateX, rateY, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveColorTemperature)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint moveMode, jint rate, jint colorTemperatureMinimum,
jint colorTemperatureMaximum, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveColorTemperature(onSuccess->Cancel(), onFailure->Cancel(), moveMode, rate, colorTemperatureMinimum,
colorTemperatureMaximum, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveHue)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint moveMode, jint rate, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveHue(onSuccess->Cancel(), onFailure->Cancel(), moveMode, rate, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveSaturation)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint moveMode, jint rate, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveSaturation(onSuccess->Cancel(), onFailure->Cancel(), moveMode, rate, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveToColor)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint colorX, jint colorY, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToColor(onSuccess->Cancel(), onFailure->Cancel(), colorX, colorY, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveToColorTemperature)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint colorTemperature, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToColorTemperature(onSuccess->Cancel(), onFailure->Cancel(), colorTemperature, transitionTime,
optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveToHue)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint hue, jint direction, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToHue(onSuccess->Cancel(), onFailure->Cancel(), hue, direction, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveToHueAndSaturation)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint hue, jint saturation, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToHueAndSaturation(onSuccess->Cancel(), onFailure->Cancel(), hue, saturation, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, moveToSaturation)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint saturation, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToSaturation(onSuccess->Cancel(), onFailure->Cancel(), saturation, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, stepColor)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepX, jint stepY, jint transitionTime, jint optionsMask,
jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err =
cppCluster->StepColor(onSuccess->Cancel(), onFailure->Cancel(), stepX, stepY, transitionTime, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, stepColorTemperature)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepMode, jint stepSize, jint transitionTime,
jint colorTemperatureMinimum, jint colorTemperatureMaximum, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StepColorTemperature(onSuccess->Cancel(), onFailure->Cancel(), stepMode, stepSize, transitionTime,
colorTemperatureMinimum, colorTemperatureMaximum, optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, stepHue)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepMode, jint stepSize, jint transitionTime,
jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StepHue(onSuccess->Cancel(), onFailure->Cancel(), stepMode, stepSize, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, stepSaturation)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepMode, jint stepSize, jint transitionTime,
jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StepSaturation(onSuccess->Cancel(), onFailure->Cancel(), stepMode, stepSize, transitionTime, optionsMask,
optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ColorControlCluster, stopMoveStep)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint optionsMask, jint optionsOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ColorControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ColorControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StopMoveStep(onSuccess->Cancel(), onFailure->Cancel(), optionsMask, optionsOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, ContentLauncherCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ContentLauncherCluster * cppCluster = new ContentLauncherCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ContentLauncherCluster, launchContent)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint autoPlay, jstring data)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ContentLauncherCluster * cppCluster;
JniUtfString dataStr(env, data);
CHIPContentLauncherClusterLaunchContentResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ContentLauncherCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPContentLauncherClusterLaunchContentResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->LaunchContent(onSuccess->Cancel(), onFailure->Cancel(), autoPlay,
chip::ByteSpan((const uint8_t *) data, strlen(dataStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ContentLauncherCluster, launchURL)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring contentURL, jstring displayString)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ContentLauncherCluster * cppCluster;
JniUtfString contentURLStr(env, contentURL);
JniUtfString displayStringStr(env, displayString);
CHIPContentLauncherClusterLaunchURLResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ContentLauncherCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPContentLauncherClusterLaunchURLResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->LaunchURL(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) contentURL, strlen(contentURLStr.c_str())),
chip::ByteSpan((const uint8_t *) displayString, strlen(displayStringStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, DescriptorCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
DescriptorCluster * cppCluster = new DescriptorCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, DiagnosticLogsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
DiagnosticLogsCluster * cppCluster = new DiagnosticLogsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, DiagnosticLogsCluster, retrieveLogsRequest)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint intent, jint requestedProtocol,
jbyteArray transferFileDesignator)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DiagnosticLogsCluster * cppCluster;
JniByteArray transferFileDesignatorArr(env, transferFileDesignator);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DiagnosticLogsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RetrieveLogsRequest(
onSuccess->Cancel(), onFailure->Cancel(), intent, requestedProtocol,
chip::ByteSpan((const uint8_t *) transferFileDesignatorArr.data(), transferFileDesignatorArr.size()));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, DoorLockCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
DoorLockCluster * cppCluster = new DoorLockCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, DoorLockCluster, clearAllPins)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearAllPinsResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearAllPinsResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearAllPins(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearAllRfids)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearAllRfidsResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearAllRfidsResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearAllRfids(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearHolidaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearHolidayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearHolidayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearHolidaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearPin)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearPinResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearPinResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearPin(onSuccess->Cancel(), onFailure->Cancel(), userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearRfid)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearRfidResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearRfidResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearRfid(onSuccess->Cancel(), onFailure->Cancel(), userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearWeekdaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearWeekdayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearWeekdayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearWeekdaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, clearYeardaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterClearYeardayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterClearYeardayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearYeardaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getHolidaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetHolidayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetHolidayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetHolidaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getLogRecord)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint logIndex)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetLogRecordResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetLogRecordResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetLogRecord(onSuccess->Cancel(), onFailure->Cancel(), logIndex);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getPin)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetPinResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetPinResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetPin(onSuccess->Cancel(), onFailure->Cancel(), userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getRfid)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetRfidResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetRfidResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetRfid(onSuccess->Cancel(), onFailure->Cancel(), userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getUserType)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetUserTypeResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetUserTypeResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetUserType(onSuccess->Cancel(), onFailure->Cancel(), userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getWeekdaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetWeekdayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetWeekdayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetWeekdaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, getYeardaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterGetYeardayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterGetYeardayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetYeardaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, lockDoor)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring pin)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
JniUtfString pinStr(env, pin);
CHIPDoorLockClusterLockDoorResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterLockDoorResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->LockDoor(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) pin, strlen(pinStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setHolidaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jlong localStartTime, jlong localEndTime,
jint operatingModeDuringHoliday)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterSetHolidayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetHolidayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetHolidaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, localStartTime, localEndTime,
operatingModeDuringHoliday);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setPin)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId, jint userStatus, jint userType, jstring pin)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
JniUtfString pinStr(env, pin);
CHIPDoorLockClusterSetPinResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetPinResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetPin(onSuccess->Cancel(), onFailure->Cancel(), userId, userStatus, userType,
chip::ByteSpan((const uint8_t *) pin, strlen(pinStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setRfid)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId, jint userStatus, jint userType, jstring id)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
JniUtfString idStr(env, id);
CHIPDoorLockClusterSetRfidResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetRfidResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetRfid(onSuccess->Cancel(), onFailure->Cancel(), userId, userStatus, userType,
chip::ByteSpan((const uint8_t *) id, strlen(idStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setUserType)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint userId, jint userType)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterSetUserTypeResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetUserTypeResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetUserType(onSuccess->Cancel(), onFailure->Cancel(), userId, userType);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setWeekdaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId, jint daysMask, jint startHour,
jint startMinute, jint endHour, jint endMinute)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterSetWeekdayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetWeekdayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetWeekdaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId, daysMask, startHour,
startMinute, endHour, endMinute);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, setYeardaySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint scheduleId, jint userId, jlong localStartTime,
jlong localEndTime)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
CHIPDoorLockClusterSetYeardayScheduleResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterSetYeardayScheduleResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err =
cppCluster->SetYeardaySchedule(onSuccess->Cancel(), onFailure->Cancel(), scheduleId, userId, localStartTime, localEndTime);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, unlockDoor)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring pin)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
JniUtfString pinStr(env, pin);
CHIPDoorLockClusterUnlockDoorResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterUnlockDoorResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UnlockDoor(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) pin, strlen(pinStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, DoorLockCluster, unlockWithTimeout)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint timeoutInSeconds, jstring pin)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
DoorLockCluster * cppCluster;
JniUtfString pinStr(env, pin);
CHIPDoorLockClusterUnlockWithTimeoutResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<DoorLockCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDoorLockClusterUnlockWithTimeoutResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UnlockWithTimeout(onSuccess->Cancel(), onFailure->Cancel(), timeoutInSeconds,
chip::ByteSpan((const uint8_t *) pin, strlen(pinStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, EthernetNetworkDiagnosticsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
EthernetNetworkDiagnosticsCluster * cppCluster = new EthernetNetworkDiagnosticsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, EthernetNetworkDiagnosticsCluster, resetCounts)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
EthernetNetworkDiagnosticsCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<EthernetNetworkDiagnosticsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ResetCounts(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, FixedLabelCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
FixedLabelCluster * cppCluster = new FixedLabelCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, GeneralCommissioningCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
GeneralCommissioningCluster * cppCluster = new GeneralCommissioningCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, GeneralCommissioningCluster, armFailSafe)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint expiryLengthSeconds, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GeneralCommissioningCluster * cppCluster;
CHIPGeneralCommissioningClusterArmFailSafeResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GeneralCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGeneralCommissioningClusterArmFailSafeResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ArmFailSafe(onSuccess->Cancel(), onFailure->Cancel(), expiryLengthSeconds, breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GeneralCommissioningCluster, commissioningComplete)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GeneralCommissioningCluster * cppCluster;
CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GeneralCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGeneralCommissioningClusterCommissioningCompleteResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->CommissioningComplete(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GeneralCommissioningCluster, setRegulatoryConfig)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint location, jstring countryCode, jlong breadcrumb,
jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GeneralCommissioningCluster * cppCluster;
JniUtfString countryCodeStr(env, countryCode);
CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GeneralCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGeneralCommissioningClusterSetRegulatoryConfigResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetRegulatoryConfig(onSuccess->Cancel(), onFailure->Cancel(), location,
chip::ByteSpan((const uint8_t *) countryCode, strlen(countryCodeStr.c_str())), breadcrumb,
timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, GeneralDiagnosticsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
GeneralDiagnosticsCluster * cppCluster = new GeneralDiagnosticsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, GroupKeyManagementCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
GroupKeyManagementCluster * cppCluster = new GroupKeyManagementCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, GroupsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
GroupsCluster * cppCluster = new GroupsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, GroupsCluster, addGroup)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jstring groupName)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
JniUtfString groupNameStr(env, groupName);
CHIPGroupsClusterAddGroupResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGroupsClusterAddGroupResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddGroup(onSuccess->Cancel(), onFailure->Cancel(), groupId,
chip::ByteSpan((const uint8_t *) groupName, strlen(groupNameStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GroupsCluster, addGroupIfIdentifying)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jstring groupName)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
JniUtfString groupNameStr(env, groupName);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddGroupIfIdentifying(onSuccess->Cancel(), onFailure->Cancel(), groupId,
chip::ByteSpan((const uint8_t *) groupName, strlen(groupNameStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GroupsCluster, getGroupMembership)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupCount, jint groupList)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
CHIPGroupsClusterGetGroupMembershipResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGroupsClusterGetGroupMembershipResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetGroupMembership(onSuccess->Cancel(), onFailure->Cancel(), groupCount, groupList);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GroupsCluster, removeAllGroups)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveAllGroups(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GroupsCluster, removeGroup)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
CHIPGroupsClusterRemoveGroupResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGroupsClusterRemoveGroupResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveGroup(onSuccess->Cancel(), onFailure->Cancel(), groupId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, GroupsCluster, viewGroup)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
GroupsCluster * cppCluster;
CHIPGroupsClusterViewGroupResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<GroupsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPGroupsClusterViewGroupResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ViewGroup(onSuccess->Cancel(), onFailure->Cancel(), groupId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, IdentifyCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
IdentifyCluster * cppCluster = new IdentifyCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, IdentifyCluster, identify)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint identifyTime)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
IdentifyCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<IdentifyCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Identify(onSuccess->Cancel(), onFailure->Cancel(), identifyTime);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, IdentifyCluster, identifyQuery)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
IdentifyCluster * cppCluster;
CHIPIdentifyClusterIdentifyQueryResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<IdentifyCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPIdentifyClusterIdentifyQueryResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->IdentifyQuery(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, KeypadInputCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
KeypadInputCluster * cppCluster = new KeypadInputCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, KeypadInputCluster, sendKey)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint keyCode)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
KeypadInputCluster * cppCluster;
CHIPKeypadInputClusterSendKeyResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<KeypadInputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPKeypadInputClusterSendKeyResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SendKey(onSuccess->Cancel(), onFailure->Cancel(), keyCode);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, LevelControlCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
LevelControlCluster * cppCluster = new LevelControlCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, LevelControlCluster, move)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint moveMode, jint rate, jint optionMask, jint optionOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Move(onSuccess->Cancel(), onFailure->Cancel(), moveMode, rate, optionMask, optionOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, moveToLevel)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint level, jint transitionTime, jint optionMask,
jint optionOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToLevel(onSuccess->Cancel(), onFailure->Cancel(), level, transitionTime, optionMask, optionOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, moveToLevelWithOnOff)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint level, jint transitionTime)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveToLevelWithOnOff(onSuccess->Cancel(), onFailure->Cancel(), level, transitionTime);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, moveWithOnOff)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint moveMode, jint rate)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MoveWithOnOff(onSuccess->Cancel(), onFailure->Cancel(), moveMode, rate);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, step)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepMode, jint stepSize, jint transitionTime, jint optionMask,
jint optionOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err =
cppCluster->Step(onSuccess->Cancel(), onFailure->Cancel(), stepMode, stepSize, transitionTime, optionMask, optionOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, stepWithOnOff)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint stepMode, jint stepSize, jint transitionTime)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StepWithOnOff(onSuccess->Cancel(), onFailure->Cancel(), stepMode, stepSize, transitionTime);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, stop)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint optionMask, jint optionOverride)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Stop(onSuccess->Cancel(), onFailure->Cancel(), optionMask, optionOverride);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, LevelControlCluster, stopWithOnOff)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LevelControlCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LevelControlCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StopWithOnOff(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, LowPowerCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
LowPowerCluster * cppCluster = new LowPowerCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, LowPowerCluster, sleep)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
LowPowerCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<LowPowerCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Sleep(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, MediaInputCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
MediaInputCluster * cppCluster = new MediaInputCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, MediaInputCluster, hideInputStatus)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaInputCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaInputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->HideInputStatus(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaInputCluster, renameInput)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint index, jstring name)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaInputCluster * cppCluster;
JniUtfString nameStr(env, name);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaInputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RenameInput(onSuccess->Cancel(), onFailure->Cancel(), index,
chip::ByteSpan((const uint8_t *) name, strlen(nameStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaInputCluster, selectInput)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint index)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaInputCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaInputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SelectInput(onSuccess->Cancel(), onFailure->Cancel(), index);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaInputCluster, showInputStatus)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaInputCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaInputCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ShowInputStatus(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, MediaPlaybackCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
MediaPlaybackCluster * cppCluster = new MediaPlaybackCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, MediaPlaybackCluster, mediaFastForward)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaFastForwardResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaFastForwardResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaFastForward(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaNext)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaNextResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaNextResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaNext(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaPause)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaPauseResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaPauseResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaPause(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaPlay)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaPlayResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaPlayResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaPlay(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaPrevious)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaPreviousResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaPreviousResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaPrevious(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaRewind)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaRewindResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaRewindResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaRewind(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaSkipBackward)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong deltaPositionMilliseconds)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaSkipBackwardResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaSkipBackward(onSuccess->Cancel(), onFailure->Cancel(), deltaPositionMilliseconds);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaSkipForward)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong deltaPositionMilliseconds)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaSkipForwardResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaSkipForward(onSuccess->Cancel(), onFailure->Cancel(), deltaPositionMilliseconds);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaSkipSeek)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong position)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaSkipSeekResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaSkipSeek(onSuccess->Cancel(), onFailure->Cancel(), position);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaStartOver)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaStartOverResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaStartOverResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaStartOver(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, MediaPlaybackCluster, mediaStop)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
MediaPlaybackCluster * cppCluster;
CHIPMediaPlaybackClusterMediaStopResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<MediaPlaybackCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPMediaPlaybackClusterMediaStopResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->MediaStop(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, NetworkCommissioningCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
NetworkCommissioningCluster * cppCluster = new NetworkCommissioningCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, NetworkCommissioningCluster, addThreadNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray operationalDataset, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray operationalDatasetArr(env, operationalDataset);
CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterAddThreadNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddThreadNetwork(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) operationalDatasetArr.data(), operationalDatasetArr.size()),
breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, addWiFiNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray ssid, jbyteArray credentials, jlong breadcrumb,
jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray ssidArr(env, ssid);
JniByteArray credentialsArr(env, credentials);
CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterAddWiFiNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddWiFiNetwork(
onSuccess->Cancel(), onFailure->Cancel(), chip::ByteSpan((const uint8_t *) ssidArr.data(), ssidArr.size()),
chip::ByteSpan((const uint8_t *) credentialsArr.data(), credentialsArr.size()), breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, disableNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray networkID, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray networkIDArr(env, networkID);
CHIPNetworkCommissioningClusterDisableNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterDisableNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->DisableNetwork(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) networkIDArr.data(), networkIDArr.size()), breadcrumb,
timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, enableNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray networkID, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray networkIDArr(env, networkID);
CHIPNetworkCommissioningClusterEnableNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterEnableNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->EnableNetwork(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) networkIDArr.data(), networkIDArr.size()), breadcrumb,
timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, getLastNetworkCommissioningResult)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetLastNetworkCommissioningResult(onSuccess->Cancel(), onFailure->Cancel(), timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, removeNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray networkID, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray networkIDArr(env, networkID);
CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterRemoveNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveNetwork(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) networkIDArr.data(), networkIDArr.size()), breadcrumb,
timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, scanNetworks)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray ssid, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray ssidArr(env, ssid);
CHIPNetworkCommissioningClusterScanNetworksResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterScanNetworksResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ScanNetworks(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) ssidArr.data(), ssidArr.size()), breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, updateThreadNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray operationalDataset, jlong breadcrumb, jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray operationalDatasetArr(env, operationalDataset);
CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterUpdateThreadNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UpdateThreadNetwork(
onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) operationalDatasetArr.data(), operationalDatasetArr.size()), breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, NetworkCommissioningCluster, updateWiFiNetwork)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray ssid, jbyteArray credentials, jlong breadcrumb,
jlong timeoutMs)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
NetworkCommissioningCluster * cppCluster;
JniByteArray ssidArr(env, ssid);
JniByteArray credentialsArr(env, credentials);
CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<NetworkCommissioningCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPNetworkCommissioningClusterUpdateWiFiNetworkResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UpdateWiFiNetwork(
onSuccess->Cancel(), onFailure->Cancel(), chip::ByteSpan((const uint8_t *) ssidArr.data(), ssidArr.size()),
chip::ByteSpan((const uint8_t *) credentialsArr.data(), credentialsArr.size()), breadcrumb, timeoutMs);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, OtaSoftwareUpdateServerCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
OtaSoftwareUpdateServerCluster * cppCluster = new OtaSoftwareUpdateServerCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, OtaSoftwareUpdateServerCluster, applyUpdateRequest)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray updateToken, jlong newVersion)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OtaSoftwareUpdateServerCluster * cppCluster;
JniByteArray updateTokenArr(env, updateToken);
CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OtaSoftwareUpdateServerCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOtaSoftwareUpdateServerClusterApplyUpdateRequestResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err =
cppCluster->ApplyUpdateRequest(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) updateTokenArr.data(), updateTokenArr.size()), newVersion);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OtaSoftwareUpdateServerCluster, notifyUpdateApplied)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray updateToken, jlong currentVersion)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OtaSoftwareUpdateServerCluster * cppCluster;
JniByteArray updateTokenArr(env, updateToken);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OtaSoftwareUpdateServerCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->NotifyUpdateApplied(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) updateTokenArr.data(), updateTokenArr.size()),
currentVersion);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OtaSoftwareUpdateServerCluster, queryImage)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint vendorId, jint productId, jint imageType,
jint hardwareVersion, jlong currentVersion, jint protocolsSupported, jstring location, jint clientCanConsent,
jbyteArray metadataForServer)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OtaSoftwareUpdateServerCluster * cppCluster;
JniUtfString locationStr(env, location);
JniByteArray metadataForServerArr(env, metadataForServer);
CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OtaSoftwareUpdateServerCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOtaSoftwareUpdateServerClusterQueryImageResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->QueryImage(onSuccess->Cancel(), onFailure->Cancel(), vendorId, productId, imageType, hardwareVersion,
currentVersion, protocolsSupported,
chip::ByteSpan((const uint8_t *) location, strlen(locationStr.c_str())), clientCanConsent,
chip::ByteSpan((const uint8_t *) metadataForServerArr.data(), metadataForServerArr.size()));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, OnOffCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
OnOffCluster * cppCluster = new OnOffCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, OnOffCluster, off)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OnOffCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OnOffCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Off(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OnOffCluster, on)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OnOffCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OnOffCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->On(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OnOffCluster, toggle)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OnOffCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OnOffCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Toggle(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, OperationalCredentialsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
OperationalCredentialsCluster * cppCluster = new OperationalCredentialsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, OperationalCredentialsCluster, addOpCert)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray operationalCert, jbyteArray iPKValue,
jlong caseAdminNode, jint adminVendorId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
JniByteArray operationalCertArr(env, operationalCert);
JniByteArray iPKValueArr(env, iPKValue);
CHIPOperationalCredentialsClusterOpCertResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOperationalCredentialsClusterOpCertResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddOpCert(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) operationalCertArr.data(), operationalCertArr.size()),
chip::ByteSpan((const uint8_t *) iPKValueArr.data(), iPKValueArr.size()), caseAdminNode,
adminVendorId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, addTrustedRootCertificate)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray rootCertificate)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
JniByteArray rootCertificateArr(env, rootCertificate);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddTrustedRootCertificate(
onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) rootCertificateArr.data(), rootCertificateArr.size()));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, opCSRRequest)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray cSRNonce)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
JniByteArray cSRNonceArr(env, cSRNonce);
CHIPOperationalCredentialsClusterOpCSRResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOperationalCredentialsClusterOpCSRResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->OpCSRRequest(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) cSRNonceArr.data(), cSRNonceArr.size()));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, removeAllFabrics)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveAllFabrics(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, removeFabric)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jlong fabricId, jlong nodeId, jint vendorId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
CHIPOperationalCredentialsClusterOpCertResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOperationalCredentialsClusterOpCertResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveFabric(onSuccess->Cancel(), onFailure->Cancel(), fabricId, nodeId, vendorId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, removeTrustedRootCertificate)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jbyteArray trustedRootIdentifier)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
JniByteArray trustedRootIdentifierArr(env, trustedRootIdentifier);
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveTrustedRootCertificate(
onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) trustedRootIdentifierArr.data(), trustedRootIdentifierArr.size()));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, setFabric)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint vendorId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
CHIPOperationalCredentialsClusterSetFabricResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOperationalCredentialsClusterSetFabricResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetFabric(onSuccess->Cancel(), onFailure->Cancel(), vendorId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, OperationalCredentialsCluster, updateFabricLabel)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring label)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
OperationalCredentialsCluster * cppCluster;
JniUtfString labelStr(env, label);
CHIPOperationalCredentialsClusterOpCertResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<OperationalCredentialsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPOperationalCredentialsClusterOpCertResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UpdateFabricLabel(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) label, strlen(labelStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, PressureMeasurementCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
PressureMeasurementCluster * cppCluster = new PressureMeasurementCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, PumpConfigurationAndControlCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
PumpConfigurationAndControlCluster * cppCluster = new PumpConfigurationAndControlCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, RelativeHumidityMeasurementCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
RelativeHumidityMeasurementCluster * cppCluster = new RelativeHumidityMeasurementCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, ScenesCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ScenesCluster * cppCluster = new ScenesCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ScenesCluster, addScene)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jint sceneId, jint transitionTime, jstring sceneName,
jint clusterId, jint length, jint value)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
JniUtfString sceneNameStr(env, sceneName);
CHIPScenesClusterAddSceneResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterAddSceneResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->AddScene(onSuccess->Cancel(), onFailure->Cancel(), groupId, sceneId, transitionTime,
chip::ByteSpan((const uint8_t *) sceneName, strlen(sceneNameStr.c_str())), clusterId, length, value);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, getSceneMembership)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPScenesClusterGetSceneMembershipResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterGetSceneMembershipResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetSceneMembership(onSuccess->Cancel(), onFailure->Cancel(), groupId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, recallScene)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jint sceneId, jint transitionTime)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RecallScene(onSuccess->Cancel(), onFailure->Cancel(), groupId, sceneId, transitionTime);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, removeAllScenes)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPScenesClusterRemoveAllScenesResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterRemoveAllScenesResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveAllScenes(onSuccess->Cancel(), onFailure->Cancel(), groupId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, removeScene)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jint sceneId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPScenesClusterRemoveSceneResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterRemoveSceneResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->RemoveScene(onSuccess->Cancel(), onFailure->Cancel(), groupId, sceneId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, storeScene)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jint sceneId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPScenesClusterStoreSceneResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterStoreSceneResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StoreScene(onSuccess->Cancel(), onFailure->Cancel(), groupId, sceneId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ScenesCluster, viewScene)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint groupId, jint sceneId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ScenesCluster * cppCluster;
CHIPScenesClusterViewSceneResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ScenesCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPScenesClusterViewSceneResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ViewScene(onSuccess->Cancel(), onFailure->Cancel(), groupId, sceneId);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, SoftwareDiagnosticsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
SoftwareDiagnosticsCluster * cppCluster = new SoftwareDiagnosticsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, SoftwareDiagnosticsCluster, resetWatermarks)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
SoftwareDiagnosticsCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<SoftwareDiagnosticsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ResetWatermarks(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, SwitchCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
SwitchCluster * cppCluster = new SwitchCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, TvChannelCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
TvChannelCluster * cppCluster = new TvChannelCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, TvChannelCluster, changeChannel)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jstring match)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TvChannelCluster * cppCluster;
JniUtfString matchStr(env, match);
CHIPTvChannelClusterChangeChannelResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TvChannelCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPTvChannelClusterChangeChannelResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ChangeChannel(onSuccess->Cancel(), onFailure->Cancel(),
chip::ByteSpan((const uint8_t *) match, strlen(matchStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, TvChannelCluster, changeChannelByNumber)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint majorNumber, jint minorNumber)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TvChannelCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TvChannelCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ChangeChannelByNumber(onSuccess->Cancel(), onFailure->Cancel(), majorNumber, minorNumber);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, TvChannelCluster, skipChannel)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint count)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TvChannelCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TvChannelCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SkipChannel(onSuccess->Cancel(), onFailure->Cancel(), count);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, TargetNavigatorCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
TargetNavigatorCluster * cppCluster = new TargetNavigatorCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, TargetNavigatorCluster, navigateTarget)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint target, jstring data)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TargetNavigatorCluster * cppCluster;
JniUtfString dataStr(env, data);
CHIPTargetNavigatorClusterNavigateTargetResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TargetNavigatorCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPTargetNavigatorClusterNavigateTargetResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->NavigateTarget(onSuccess->Cancel(), onFailure->Cancel(), target,
chip::ByteSpan((const uint8_t *) data, strlen(dataStr.c_str())));
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, TemperatureMeasurementCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
TemperatureMeasurementCluster * cppCluster = new TemperatureMeasurementCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, TestClusterCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
TestClusterCluster * cppCluster = new TestClusterCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, TestClusterCluster, test)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TestClusterCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TestClusterCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->Test(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, TestClusterCluster, testNotHandled)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TestClusterCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TestClusterCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->TestNotHandled(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, TestClusterCluster, testSpecific)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TestClusterCluster * cppCluster;
CHIPTestClusterClusterTestSpecificResponseCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TestClusterCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPTestClusterClusterTestSpecificResponseCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->TestSpecific(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, TestClusterCluster, testUnknownCommand)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
TestClusterCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<TestClusterCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->TestUnknownCommand(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, ThermostatCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ThermostatCluster * cppCluster = new ThermostatCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ThermostatCluster, clearWeeklySchedule)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThermostatCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThermostatCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ClearWeeklySchedule(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ThermostatCluster, getRelayStatusLog)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThermostatCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThermostatCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetRelayStatusLog(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ThermostatCluster, getWeeklySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint daysToReturn, jint modeToReturn)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThermostatCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThermostatCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GetWeeklySchedule(onSuccess->Cancel(), onFailure->Cancel(), daysToReturn, modeToReturn);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ThermostatCluster, setWeeklySchedule)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint numberOfTransitionsForSequence, jint dayOfWeekForSequence,
jint modeForSequence, jint payload)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThermostatCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThermostatCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetWeeklySchedule(onSuccess->Cancel(), onFailure->Cancel(), numberOfTransitionsForSequence,
dayOfWeekForSequence, modeForSequence, payload);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, ThermostatCluster, setpointRaiseLower)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint mode, jint amount)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThermostatCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThermostatCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->SetpointRaiseLower(onSuccess->Cancel(), onFailure->Cancel(), mode, amount);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, ThreadNetworkDiagnosticsCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
ThreadNetworkDiagnosticsCluster * cppCluster = new ThreadNetworkDiagnosticsCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, ThreadNetworkDiagnosticsCluster, resetCounts)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
ThreadNetworkDiagnosticsCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<ThreadNetworkDiagnosticsCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->ResetCounts(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(jlong, WakeOnLanCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
WakeOnLanCluster * cppCluster = new WakeOnLanCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(jlong, WindowCoveringCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
WindowCoveringCluster * cppCluster = new WindowCoveringCluster();
cppCluster->Associate(reinterpret_cast<Device *>(devicePtr), endpointId);
return reinterpret_cast<jlong>(cppCluster);
}
JNI_METHOD(void, WindowCoveringCluster, downOrClose)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->DownOrClose(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, goToLiftPercentage)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint liftPercentageValue, jint liftPercent100thsValue)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GoToLiftPercentage(onSuccess->Cancel(), onFailure->Cancel(), liftPercentageValue, liftPercent100thsValue);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, goToLiftValue)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint liftValue)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GoToLiftValue(onSuccess->Cancel(), onFailure->Cancel(), liftValue);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, goToTiltPercentage)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint tiltPercentageValue, jint tiltPercent100thsValue)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GoToTiltPercentage(onSuccess->Cancel(), onFailure->Cancel(), tiltPercentageValue, tiltPercent100thsValue);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, goToTiltValue)
(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint tiltValue)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->GoToTiltValue(onSuccess->Cancel(), onFailure->Cancel(), tiltValue);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, stopMotion)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->StopMotion(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
JNI_METHOD(void, WindowCoveringCluster, upOrOpen)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback)
{
StackLockGuard lock(JniReferences::GetInstance().GetStackLock());
CHIP_ERROR err = CHIP_NO_ERROR;
WindowCoveringCluster * cppCluster;
CHIPDefaultSuccessCallback * onSuccess;
CHIPDefaultFailureCallback * onFailure;
cppCluster = reinterpret_cast<WindowCoveringCluster *>(clusterPtr);
VerifyOrExit(cppCluster != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onSuccess = new CHIPDefaultSuccessCallback(callback);
VerifyOrExit(onSuccess != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
onFailure = new CHIPDefaultFailureCallback(callback);
VerifyOrExit(onFailure != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = cppCluster->UpOrOpen(onSuccess->Cancel(), onFailure->Cancel());
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
delete onSuccess;
delete onFailure;
jthrowable exception;
jmethodID method;
err = JniReferences::GetInstance().FindMethod(env, callback, "onError", "(Ljava/lang/Exception;)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
err = CreateIllegalStateException(env, "Error invoking cluster", err, exception);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "Error throwing IllegalStateException %d", err);
return;
}
env->CallVoidMethod(callback, method, exception);
}
}
|
[
"[email protected]"
] | |
274373ed708234ad1ed5d3732a92f876ec870322
|
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
|
/cmake-build-debug/programs_tiling/function13912/function13912_schedule_29/function13912_schedule_29_wrapper.cpp
|
88f47741e744cf3c49448c4f06a03d4017b9a3b8
|
[] |
no_license
|
IsraMekki/tiramisu_code_generator
|
8b3f1d63cff62ba9f5242c019058d5a3119184a3
|
5a259d8e244af452e5301126683fa4320c2047a3
|
refs/heads/master
| 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 857 |
cpp
|
#include "Halide.h"
#include "function13912_schedule_29_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){Halide::Buffer<int32_t> buf0(8192, 64, 128);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13912_schedule_29(buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13912/function13912_schedule_29/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
}
|
[
"[email protected]"
] | |
ef73daa177366db78e962de3781281ea630993db
|
afc3b80d0d63800953f818dee7344d01506c2be5
|
/SoftRender05-Lighting/SoftRender05-lighting.cpp
|
8e26121483394865e0ebd0a139b6e02e0d77e546
|
[] |
no_license
|
BillScott1024/Tutorial-RenderEngine
|
b19c41381404314db5c0cd40878313d94f0d3d61
|
4314b8b0880d5158f00b510a86b9c8f759be04df
|
refs/heads/master
| 2023-04-14T20:18:38.175245 | 2019-04-01T09:07:45 | 2019-04-01T09:07:45 | 112,351,606 | 0 | 0 | null | 2021-04-25T18:21:18 | 2017-11-28T15:16:12 |
C
|
GB18030
|
C++
| false | false | 3,712 |
cpp
|
#include "App.h"
#include "SoftRenderer.h"
#include <array>
using namespace X;
void CreateSphere(RenderOp * rop, int rings, int segments, float radius)
{
int vertexCount = (rings + 1) * (segments + 1);
int indexCount = rings * segments * 6;
// vertex buffer
rop->vbuffer.resize(vertexCount);
Vertex * vert = &rop->vbuffer[0];
{
float fTileRingAngle = (PI / rings);
float fTileSegAngle = (PI * 2 / segments);
float r;
short i, j;
Float3 pos, normal;
for (i = 0; i <= rings; ++i)
{
r = radius * sin(i * fTileRingAngle);
pos.y = radius * cos(i * fTileRingAngle);
for (j = 0; j <= segments; ++j)
{
pos.x = r * cos(j * fTileSegAngle);
pos.z = r * sin(j * fTileSegAngle);
normal = pos; normal.Normalize();
vert->position = pos;
vert->normal = normal;
//vert->color = Float3(1, 1, 1);
vert->color = (normal + Float3(1, 1, 1)) / 2;
++vert;
}
}
}
// index buffer
rop->ibuffer.resize(indexCount);
short * indices = &rop->ibuffer[0];
{
short row = 0, row_n = 0;
short i, j;
for (i = 0; i < rings; ++i)
{
row_n = row + segments + 1;
for (j = 0; j < segments; ++j)
{
*indices++ = row + j;
*indices++ = row + j + 1;
*indices++ = row_n + j;
*indices++ = row_n + j;
*indices++ = row + j + 1;
*indices++ = row_n + j + 1;
}
row += segments + 1;
}
}
rop->primCount = indexCount / 3;
rop->primType = ePrimType::TRI_LIST;
}
class MyApp : public App
{
SoftRenderer * mRenderer;
RenderOp * mRenderOp;
Mat4 mWorldMatrix;
Mat4 mViewMatrix;
Mat4 mProjMatrix;
public:
MyApp()
{
}
virtual ~MyApp()
{
}
virtual void OnInit(int w, int h)
{
// ๅๅปบๆธฒๆๅจ
mRenderer = new SoftRenderer(mWnd, w, h);
// ๅๅปบ็ไฝ
mRenderOp = new RenderOp;
CreateSphere(mRenderOp, 30, 30, 1);
}
virtual void OnUpdate()
{
mRenderer->Begin();
mRenderer->Clear(Float3(0, 0, 0), 1);
// ้็ๆถ้ดๆ่ฝฌ
mWorldMatrix.MakeRotation(Float3(0, 1, 0), PI * mTime * 0.3f);
// ็ธๆบ็ฉ้ต
Float3 vEye = Float3(0, 3, -3);
Float3 vAt = Float3(0, 0, 0);
Float3 vUp = Float3(0, 1, 0);
mViewMatrix.MakeViewTM(vEye, vAt, vUp);
//ๆๅฝฑ็ฉ้ต
float nearClip = 0.1f;
float farClip = 1000.0f;
float fovy = PI / 3;
float aspect = mWidth / (float)mHeight;
mProjMatrix.MakePerspectiveTM(fovy, aspect, nearClip, farClip);
// ่ฎพ็ฝฎๅๆข็ฉ้ต
mRenderer->SetWorldMatrix(mWorldMatrix);
mRenderer->SetViewMatrix(mViewMatrix);
mRenderer->SetProjMatrix(mProjMatrix);
// ่ฎพ็ฝฎ็ธๆบ
Float3 vDir = vAt - vEye;
vDir.Normalize();
mRenderer->SetCamera(vEye, vDir);
// ่ฎพ็ฝฎ็ฏๅ
Light light;
light.Type = Light::DIRECTION;
light.Direction = Float3(-1, -1, 1);
light.Diffuse = Float3(1, 1, 1);
light.Specular = Float3(1, 1, 1);
light.Direction.Normalize();
mRenderer->SetLight(&light);
// ่ฎพ็ฝฎๆ่ดจ
Material material;
material.Ambient = Float3(1, 0, 0) * 0.3f;
material.Diffuse = Float3(1, 0, 0);
material.Specular = Float3(1, 1, 1) * 0.5f;
material.SpecularPower = 20;
mRenderer->SetMaterial(material);
// ่ฎพ็ฝฎๆธฒๆ็ถๆ
RenderState rstate;
rstate.CullMode = eCullMode::BACK; // ่้ข่ฃๅช
rstate.BlendMode = eBlendMode::OPACITY; // ไธ้ๆ
rstate.DepthMode = eDepthMode::LESS_EQUAL; // ๆทฑๅบฆๆต่ฏๆจกๅผ
rstate.DepthMask = TRUE; // ๅผๅฏๆทฑๅบฆๅ
mRenderer->SetRenderState(rstate);
// ๆธฒๆ
mRenderer->Render(mRenderOp);
mRenderer->End();
// ๆไบค
mRenderer->Present();
}
virtual void OnShutdown()
{
delete mRenderOp;
delete mRenderer;
}
virtual void OnResize(int w, int h)
{
mRenderer->Resize(w, h);
}
};
void CreateApplication(App ** ppApp)
{
*ppApp = new MyApp;
}
|
[
"[email protected]"
] | |
05fff7c51f98beaeae36484c5a89874a71841bda
|
60bba5b97c84d28792a5b98b734d2fd54a78b816
|
/RobotSymbol/Win32Window.h
|
0f8ee7f523e2bf8f53c2d0e78292b94a871046dd
|
[] |
no_license
|
dkStephanos/robotSymbol
|
9f71813ce14654a6f7a890e88bc087e8e09e6d55
|
bbf87ce913b862dc51e1b3ebca16af610f8e678e
|
refs/heads/master
| 2021-07-06T14:48:53.842243 | 2017-10-02T19:32:52 | 2017-10-02T19:32:52 | 105,576,256 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 804 |
h
|
#pragma once
#ifndef WIN32_WINDOW
#define WIN32_WINDOW
#include "Windows.h"
#include "GenericWindow.h"
#include <string>
using std::string;
using std::wstring;
class ITimer;
class Win32Window :
public GenericWindow
{
protected:
wstring title;
int width, height;
HWND windowHandle;
HINSTANCE windowInstance;
WNDPROC WndProcedure;
bool timeToExit;
public:
Win32Window(wstring title, int width, int height);
virtual ~Win32Window();
bool create();
void show();
virtual void listenForEvents(ITimer* timer);
void exit() { this->timeToExit = true; }
float getAspectRatio() const { return this->width / (float)this->height; }
protected:
virtual void runOneFrame(float elapsedTimesMS) {};
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
};
#endif
|
[
"[email protected]"
] | |
af277cf8a4ecc8049ee9df5796fe7a1087fbd1f5
|
9a1080769fd517f6e64accb06acc91d1bfecf68c
|
/src/nest_stack/main.cpp
|
9ec1787f1f563f42d83b4c247483939ff2b2e0ab
|
[] |
no_license
|
ljcduo/DataStructuresInCpp
|
ac6a64fc81514ae5a58e79e9af2d8df0e423ce98
|
19b4179dc71d914d6bb631f4587db071ac00dd46
|
refs/heads/master
| 2021-01-10T08:15:55.570823 | 2015-12-05T13:15:55 | 2015-12-05T13:15:55 | 47,404,204 | 0 | 1 | null | null | null | null |
GB18030
|
C++
| false | false | 1,244 |
cpp
|
/******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, [email protected]
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2006-2013. All rights reserved.
******************************************************************************************/
#include "nest.h"
/******************************************************************************************
* ๆฃๆฅ่กจ่พพๅผๆฌๅทๆฏๅฆๅน้
******************************************************************************************/
int main(int argc, char *argv[]) {
// ๆฃๆฅๅๆฐ
if (2 > argc) { //่ณๅฐ่ฆๆไพไธไธชๅพ
ๆฃๆฅ็ๅญ็ฌฆไธฒ
fprintf(stderr, "\nUsage: %s <string#1> <string#2> ... \n", argv[0]);
fprintf(stderr, "For example %s (a[i-1][j+1])+a[i+1][j-1])*2\n", argv[0]);
return -1;
}
// ้ไธๆฃๆฅๅไธฒๆฏๅฆๅน้
for (int i = 1; i < argc; i++) {
char* s = argv[i]; printf("\nๆฃๆฅ๏ผ%s\n", s);
paren(s, 0, strlen(s)-1) ?
printf("\n%s: ๅน้
\a\n", s) :
printf("\n%s: ไธๅน้
\a\a\n", s);
getchar();
}
return 0;
}
|
[
"[email protected]"
] | |
f3c6cc39a0b0c8f489c0529770c8d6443890dd79
|
d9f4fb513ffb5f4c3eca44011add75fd767ce985
|
/src/Utils/Utils.h
|
f08350c33934107a479f26e0b05c9545e89d3d52
|
[] |
no_license
|
nikifaets/Ikko-Database
|
3648df2679e4ff64f802f12b0c08acc7374cfd18
|
5b30adbaa5fc83a1cbb67152e8c5e2e4e496ad27
|
refs/heads/master
| 2022-10-05T02:25:08.039521 | 2020-06-07T21:07:32 | 2020-06-07T21:07:32 | 258,199,571 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 902 |
h
|
#pragma once
#include <vector>
#include "../Record/RecordNumber.h"
#include "../Table/Table.h"
namespace Utils{
template<typename T>
std::vector<T> concatenate(std::vector<T> v1, std::vector<T> v2){
std::vector<T> res;
//walk through first vec
for(int i=0; i<v1.size(); i++){
res.push_back(v1[i]);
}
//walk thorugh second vec
for(int i=0; i<v2.size(); i++){
res.push_back(v2[i]);
}
return res;
}
RecordNumber* add(RecordNumber* arg, RecordNumber* val_holder);
RecordNumber* multiply(RecordNumber* arg, RecordNumber* val_holder);
RecordNumber* get_max(RecordNumber* arg, RecordNumber* val_holder);
RecordNumber* get_min(RecordNumber* arg, RecordNumber* val_holder);
RecordNumber* aggregate(Table table, std::vector<int> idx, int col, std::string operation);
}
|
[
"[email protected]"
] | |
149e801b353407ebc02900c199a2638236d3fcf7
|
8b9b1249163ca61a43f4175873594be79d0a9c03
|
/deps/boost_1_66_0/libs/mp11/test/mp_with_index_cx.cpp
|
97fdcc4ac5798e3c393c43cdfb75201eaf2f56d4
|
[
"MIT",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
maugf214/LiquidCore
|
f6632537dfb4686f4302e871d997992e6289eb65
|
80a9cce27ceaeeb3c8002c17ce638ed45410d3e6
|
refs/heads/master
| 2022-12-02T01:18:26.132951 | 2020-08-17T10:27:36 | 2020-08-17T10:27:36 | 288,151,167 | 0 | 1 |
MIT
| 2020-08-17T10:32:05 | 2020-08-17T10:32:04 | null |
UTF-8
|
C++
| false | false | 807 |
cpp
|
// Copyright 2017 Peter Dimov.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/config.hpp>
#if defined( BOOST_NO_CXX14_CONSTEXPR )
int main() {}
#else
#include <boost/mp11/algorithm.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
using boost::mp11::mp_size_t;
using boost::mp11::mp_with_index;
struct F
{
template<std::size_t I> constexpr std::size_t operator()( mp_size_t<I> ) const
{
return I;
}
};
#define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)
int main()
{
constexpr std::size_t i = mp_with_index<64>( 57, F{} );
STATIC_ASSERT( i == 57 );
}
#endif
|
[
"[email protected]"
] | |
8abd3e1c5144dfeacbbbce9b41146eabce62881f
|
6f7a080847a8117caed986c8cd9c40b855b292a0
|
/Data_processing/RGB_Data_Processing.cpp
|
566b1da31c15d08ade8355049dc3002e8aea44b0
|
[] |
no_license
|
Pwnur/FFmpeg_Learning
|
3ef8808aee254caa94d17fa72ab2ac4c255166c6
|
872e0507e62f714ab7cb4a166879958830ae5942
|
refs/heads/master
| 2020-04-11T07:24:44.657478 | 2019-02-21T11:27:58 | 2019-02-21T11:27:58 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,570 |
cpp
|
//============================================================================
// Name : RGB_Data_Processing.cpp
// Author : Hurley
// Mail : [email protected]
// Version : 1.0.0
// Create On : Dec 20, 2018
// Copyright : Copyright (c) 2018 Hurley All rights reserved.
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
/*
* @Description: ๅ็ฆปRGB24ๅ็ด ๆฐๆฎไธญ็RใGใBๅ้
* ไธๅธงๅฎฝ้ซๅๅซไธบwใh็RGB24ๅพๅไธๅ
ฑๅ ็จwidth*height*3 Byte็ๅญๅจ็ฉบ้ด
* @param: width :่ง้ขๅธง็ๅฎฝๅบฆ
* height :่ง้ขๅธง็้ซๅบฆ
* num :่ง้ขๅธงๆฐ
* @return: int
* @Author: Hurley 2018-12-13
*/
int simplest_rgb24_split(char *url, int width, int height, int num)
{
FILE *fp = fopen(url,"rb+");
FILE *fp1 = fopen("output_r.y","wb+");
FILE *fp2 = fopen("output_g.y","wb+");
FILE *fp3 = fopen("output_b.y","wb+");
unsigned char *pic=(unsigned char *)malloc(width*height*3);
for (int i = 0; i < num; i++)
{
fread(pic, 1, width*height*3, fp);
for (int j = 0; j < width*height*3; j = j+3)
{
fwrite(pic+j, 1, 1, fp1); //R
fwrite(pic+j+1, 1, 1, fp2); //G
fwrite(pic+j+2, 1, 1, fp3); //B
}
}
free(pic);
fclose(fp);
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
int simple_rgb24_to_bmp(const char *rgb24path, int width, int height, const char *bmppath)
{
typedef struct tagBITMAPFILEHEADER
{
unsigned short int bfType; //ไฝๅพๆไปถ็็ฑปๅ๏ผๅฟ
้กปไธบBM
unsigned long bfSize; //ๆไปถๅคงๅฐ๏ผไปฅๅญ่ไธบๅไฝ
unsigned short int bfReserverd1; //ไฝๅพๆไปถไฟ็ๅญ๏ผๅฟ
้กปไธบ0
unsigned short int bfReserverd2; //ไฝๅพๆไปถไฟ็ๅญ๏ผๅฟ
้กปไธบ0
unsigned long bfbfOffBits; //ไฝๅพๆไปถๅคดๅฐๆฐๆฎ็ๅ็งป้๏ผไปฅๅญ่ไธบๅไฝ
}BITMAPFILEHEADER;
typedef struct tagBITMAPINFOHEADER
{
long biSize; //่ฏฅ็ปๆๅคงๅฐ๏ผๅญ่ไธบๅไฝ
long biWidth; //ๅพๅฝขๅฎฝๅบฆไปฅ่ฑก็ด ไธบๅไฝ
long biHeight; //ๅพๅฝข้ซๅบฆไปฅ่ฑก็ด ไธบๅไฝ
short int biPlanes; //็ฎๆ ่ฎพๅค็็บงๅซ๏ผๅฟ
้กปไธบ1
short int biBitcount; //้ข่ฒๆทฑๅบฆ๏ผๆฏไธช่ฑก็ด ๆ้่ฆ็ไฝๆฐ
short int biCompression; //ไฝๅพ็ๅ็ผฉ็ฑปๅ
long biSizeImage; //ไฝๅพ็ๅคงๅฐ๏ผไปฅๅญ่ไธบๅไฝ
long biXPelsPermeter; //ไฝๅพๆฐดๅนณๅ่พจ็๏ผๆฏ็ฑณๅ็ด ๆฐ
long biYPelsPermeter; //ไฝๅพๅ็ดๅ่พจ็๏ผๆฏ็ฑณๅ็ด ๆฐ
long biClrUsed; //ไฝๅพๅฎ้
ไฝฟ็จ็้ข่ฒ่กจไธญ็้ข่ฒๆฐ
long biClrImportant; //ไฝๅพๆพ็คบ่ฟ็จไธญ้่ฆ็้ข่ฒๆฐ
}BITMAPINFOHEADER;
typedef struct
{
long imageSize;
long blank;
long startPosition;
}BmpHead;
typedef struct
{
long Length;
long width;
long height;
unsigned short colorPlane;
unsigned short bitColor;
long ZipFormat;
long realSize;
long xPels;
long yPels;
long colorUse;
long colorImportant;
}InfoHead;
int i = 0,j = 0;
BmpHead m_BMPHeader = {0};
InfoHead m_BMPInfoHeader = {0};
char bfType[2] = {'B','M'};
int header_size = sizeof(bfType) + sizeof(BmpHead) + sizeof(InfoHead);
unsigned char *rgb24_buffer = NULL;
FILE *fp_rgb24 = NULL,*fp_bmp = NULL;
if((fp_rgb24 = fopen(rgb24path,"rb")) == NULL)
{
printf("Error:Cannot open input RGB24 file.\n");
return -1;
}
if ((fp_bmp = fopen(bmppath,"wb")) == NULL)
{
printf("Error:Connot open output BMP file.\n");
return -1;
}
rgb24_buffer = (unsigned char *)malloc(width*height*3);
fread(rgb24_buffer, 1, width*height*3, fp_rgb24);
m_BMPHeader.imageSize = 3*width*height + header_size;
m_BMPHeader.startPosition = header_size;
m_BMPInfoHeader.Length = sizeof(InfoHead);
m_BMPInfoHeader.width = width;
m_BMPInfoHeader.height = height;
m_BMPInfoHeader.colorPlane = 1;
m_BMPInfoHeader.bitColor = 24;
m_BMPInfoHeader.realSize = 3*width*height;
fwrite(bfType, 1, sizeof(bfType),fp_bmp);
fwrite(&m_BMPHeader, 1, sizeof(m_BMPInfoHeader), fp_bmp);
fwrite(&m_BMPInfoHeader, 1, sizeof(m_BMPInfoHeader),fp_bmp);
for (j = 0;j < height; j++)
{
for(i = 0; i < width; i++)
{
char temp = rgb24_buffer[(j*width+i)*3 + 2];
rgb24_buffer[(j*width+i)*3+2]=rgb24_buffer[(j*width+i)*3+0];
rgb24_buffer[(j*width+i)*3+0]=temp;
}
}
fwrite(rgb24_buffer, 3*width*height, 1, fp_bmp);
fclose(fp_rgb24);
fclose(fp_bmp);
free(rgb24_buffer);
printf("Finish generate %s!\n",bmppath);
return 0;
}
unsigned char clip_value(unsigned char x, unsigned char min_val, unsigned char max_val)
{
if (x > max_val)
return max_val;
else if (x < min_val)
return min_val;
else
return x;
}
//RGBๅฐYUV็่ฝฌๆขๅ
ฌๅผ
//Y = 0.299*R+0.587*G+0.114*B
//U =-0.147*R-0.289*G+0.463*B
//V = 0.615*R-0.515*G-0.100*B
bool RGB24_TO_YUV420(unsigned char *RgbBuf, int width, int height, unsigned char *yuvBuf)
{
unsigned char *ptrY,*ptrU,*ptrV,*ptrRGB;
memset(yuvBuf, 0, width*height*3/2);
ptrY = yuvBuf;
ptrU = yuvBuf + width*height;
ptrV = ptrU + (width*height*1/4);
unsigned char y,u,v,r,g,b;
for (int j = 0;j<height;j++)
{
ptrRGB = RgbBuf + width*height*3;
for (int i=0;i<width;i++)
{
r = *(ptrRGB++);
g = *(ptrRGB++);
b = *(ptrRGB++);
y = (unsigned char)( ( 66 * r + 129 * g + 25 * b + 128) >> 8) + 16;
u = (unsigned char)( ( -38 * r - 74 * g + 112 * b + 128) >> 8) + 128 ;
v = (unsigned char)( ( 112 * r - 94 * g - 18 * b + 128) >> 8) + 128 ;
*(ptrY++) = clip_value(y,0,255);
if (j%2==0&&i%2 ==0)
{
*(ptrU++) =clip_value(u,0,255);
}
else
{
if (i%2==0)
{
*(ptrV++) =clip_value(v,0,255);
}
}
}
}
return true;
}
/**
* Convert RGB24 file to YUV420P file
* @param url_in Location of Input RGB file.
* @param w Width of Input RGB file.
* @param h Height of Input RGB file.
* @param num Number of frames to process.
* @param url_out Location of Output YUV file.
*/
int simplest_rgb24_to_yuv420(char *url_in, int w, int h,int num,char *url_out){
FILE *fp=fopen(url_in,"rb+");
FILE *fp1=fopen(url_out,"wb+");
unsigned char *pic_rgb24=(unsigned char *)malloc(w*h*3);
unsigned char *pic_yuv420=(unsigned char *)malloc(w*h*3/2);
for(int i=0;i<num;i++){
fread(pic_rgb24,1,w*h*3,fp);
RGB24_TO_YUV420(pic_rgb24,w,h,pic_yuv420);
fwrite(pic_yuv420,1,w*h*3/2,fp1);
}
free(pic_rgb24);
free(pic_yuv420);
fclose(fp);
fclose(fp1);
return 0;
}
|
[
"linxl @ [email protected]"
] |
linxl @ [email protected]
|
8588e80ed2e35664aaa39a807fe67ab70b9614d4
|
6b550d3d0b182bcddda1f0a175d6b6cd07b60fb3
|
/logdevice/common/protocol/SHUTDOWN_Message.cpp
|
dfb5f2fe428827ca8f4ffa433eded723429af981
|
[
"BSD-3-Clause"
] |
permissive
|
Rachelmorrell/LogDevice
|
5bd04f7ab0bdf9cc6e5b2da4a4b51210cdc9a4c8
|
3a8d800033fada47d878b64533afdf41dc79e057
|
refs/heads/master
| 2021-06-24T09:10:20.240011 | 2020-04-21T14:10:52 | 2020-04-21T14:13:09 | 157,563,026 | 1 | 0 |
NOASSERTION
| 2020-04-21T19:20:55 | 2018-11-14T14:43:33 |
C++
|
UTF-8
|
C++
| false | false | 1,593 |
cpp
|
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/protocol/SHUTDOWN_Message.h"
#include "logdevice/common/Processor.h"
#include "logdevice/common/RebuildingTypes.h"
#include "logdevice/common/Sender.h"
#include "logdevice/common/Worker.h"
namespace facebook { namespace logdevice {
SHUTDOWN_Message::SHUTDOWN_Message(const SHUTDOWN_Header& header)
: Message(MessageType::SHUTDOWN, TrafficClass::FAILURE_DETECTOR),
header_(header) {}
void SHUTDOWN_Message::serialize(ProtocolWriter& writer) const {
writer.write(header_);
}
MessageReadResult SHUTDOWN_Message::deserialize(ProtocolReader& reader) {
SHUTDOWN_Header hdr;
hdr.serverInstanceId = ServerInstanceId_INVALID;
reader.read(&hdr);
auto m = std::make_unique<SHUTDOWN_Message>(hdr);
return reader.resultMsg(std::move(m));
}
Message::Disposition SHUTDOWN_Message::onReceived(const Address& from) {
ld_debug(
"Received SHUTDOWN Message from %s", from.id_.node_.toString().c_str());
if (from.isClientAddress()) {
ld_error("PROTOCOL ERROR: got a SHUTDOWN message from %s - a "
"client address. Ignoring",
Sender::describeConnection(from).c_str());
err = E::PROTO;
return Disposition::ERROR;
}
Worker* w = Worker::onThisThread();
w->sender().setPeerShuttingDown(from.asNodeID());
return Disposition::NORMAL;
}
}} // namespace facebook::logdevice
|
[
"[email protected]"
] | |
f391225c1e145ef5e27a2082b0b17893da4d172c
|
cbac959d1f5549c333e6cf9b8da8756c2b2893e8
|
/old/lGame/lSpaceShooter/lMap.cpp
|
21cb792f0eabab24a34919ec51b9501f6bec8b0d
|
[] |
no_license
|
sereslorant/SpaceShooter
|
74baed83f4fda37a48e0182b4cbf1a5c0d6781b1
|
417a8e387b8b3b2d4b8d614cb192d5bbea56846d
|
refs/heads/master
| 2020-05-26T05:12:10.573923 | 2019-02-24T19:29:26 | 2019-02-24T19:29:26 | 82,465,024 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,845 |
cpp
|
#include "lMap.h"
#include "../../lMath/lmGeometry2D.h"
#include "lSpaceShooter.h"
using namespace std;
lRect *lMap::lTerrain::lTile::GetRect()
{
return Rect;
}
/*
void lMap::lTerrain::lTile::MoveY(float dy)
{
Rect->SetY(Rect->GetPosition().Y + dy);
}
*/
lMap::lTerrain::lTile::lTile(lRect *rect)
:Rect(rect)
{
}
lMap::lTerrain::lTile::~lTile()
{
delete Rect;
}
lMap::lTerrain::lTile **lMap::lTerrain::operator [](unsigned int i)
{
return Terrain[i];
}
void lMap::lTerrain::Draw()
{
for(unsigned int i=0;i < Height;i++)
{
for(unsigned int j=0;j < Width;j++)
{
if(Terrain[i][j] != nullptr)
{
Terrain[i][j]->GetRect()->Draw();
}
}
}
}
lMap::lTerrain::lTerrain(unsigned int width,unsigned int height)
:Width(width),Height(height)
{
Terrain = new lTile **[Height];
for(unsigned int i=0;i < Height;i++)
{
Terrain[i] = new lTile *[Width];
}
}
lMap::lTerrain::~lTerrain()
{
for(unsigned int i=0;i < Height;i++)
{
for(unsigned int j=0;j < Width;j++)
{
if(Terrain[i][j] != nullptr)
{
delete Terrain[i][j];
}
}
delete Terrain[i];
}
delete Terrain;
}
const std::list<lObject *> &lMap::GetObjects() const
{
return Objects;
}
const std::list<lProjectile *> &lMap::GetProjectiles() const
{
return Projectiles;
}
void lMap::AddObject(lObject *Object)
{
Objects.push_back(Object);
}
void lMap::DeleteObject(lObject *Object)
{
for(auto I = Objects.begin();I != Objects.end();I++)
{
if(*I == Object)
{
Objects.erase(I);
break;
}
}
}
void lMap::AddProjectile(lProjectile *Projectile)
{
Projectiles.push_back(Projectile);
}
void lMap::Step(float dt,lRect *Viewport)
{
Background->SetPosition(Viewport->GetPosition());
//CHECK_COLLISION
for(auto I = Objects.begin();I != Objects.end();I++)
{
for(auto J = next(I);J != Objects.end();J++)
{
if((*J)->IsAlive() == false)
{
continue;
}
const lmVector2D &I_Min = (*I)->GetRect()->GetPosition();
lmVector2D I_Max = I_Min + lmVector2D((*I)->GetRect()->GetWidth(),(*I)->GetRect()->GetHeight());
const lmVector2D &J_Min = (*J)->GetRect()->GetPosition();
lmVector2D J_Max = J_Min + lmVector2D((*J)->GetRect()->GetWidth(),(*J)->GetRect()->GetHeight());
if(lmAABBAABBIntersection(I_Min,I_Max,J_Min,J_Max))
{
if((*I)->GetSpecies() != (*J)->GetSpecies())
{
float I_ColDmg = (*I)->GetCollisionDamage();
float J_ColDmg = (*J)->GetCollisionDamage();
(*I)->TakeDamage(J_ColDmg);
(*J)->TakeDamage(I_ColDmg);
}
}
}
}
for(auto I = Projectiles.begin();I != Projectiles.end(); )
{
bool Collides = false;
float MinMlt;
lmVector2D MinPoI;
list<lObject *>::iterator K;
for(auto J = Objects.begin();J != Objects.end();J++)
{
if((*J)->IsAlive() == false)
{
continue;
}
float Mlt;
lmVector2D PofImpact;
if((*I)->GetSpecies() != (*J)->GetSpecies())
{
if(CheckCollision((*J)->GetRect(),(*I)->GetTrajectory(),&Mlt,&PofImpact))
{
if(Mlt < ((*I)->GetSpeed() * dt) && Mlt > 0)
{
if(Collides != true)
{
Collides = true;
MinMlt = Mlt;
MinPoI = PofImpact;
K = J;
}
else
{
if(Mlt < MinMlt)
{
MinMlt = Mlt;
MinPoI = PofImpact;
K = J;
}
}
}
}
}
}
const lmVector2D &ViewportMin = Viewport->GetPosition();
lmVector2D ViewportMax = ViewportMin + lmVector2D(Viewport->GetWidth(),Viewport->GetHeight());
if(Collides || !lmPointAABBIntersection((*I)->GetTrajectory()->GetPosition(),ViewportMin,ViewportMax))
{
if(Collides)
{
(*K)->TakeDamage((*I)->GetDamage());
cout << "Talalat " << (*I)->GetDamage() << " PofImpact: " << MinPoI.X << ";" << MinPoI.Y << endl;
}
else
{
cout << "Megpusztult " << (*I)->GetDamage() << endl;
}
auto L = I;
I++;
Projectiles.erase(L);
}
else
{
I++;
}
}
//UPDATE
for(auto I = Objects.begin();I != Objects.end(); )
{
if((*I)->IsAlive() == false)
{
auto K = I;
I++;
cout << "Points earned " << (*K)->GetPoints() << endl;
Game->AddPoints(((*K)->GetPoints()));
Objects.erase(K);
cout << "Egy objektum megpusztult" << endl;
}
else
{
(*I)->Update(dt);
(*I)->UpdateRect();
I++;
}
}
for(auto I = Projectiles.begin();I != Projectiles.end();I++)
{
(*I)->Update(dt);
}
}
void lMap::Draw()
{
glMatrixMode(GL_MODELVIEW);
Background->Draw();
Terrain->Draw();
for(auto I = Objects.begin();I != Objects.end();I++)
{
(*I)->Draw();
}
for(auto I = Projectiles.begin();I != Projectiles.end();I++)
{
(*I)->Draw();
}
}
lMap::lMap(lSpaceShooter *game,float Width,float Height,RM &resource_manager,const std::string &content_directory,const std::string &map_name)
:Game(game)
{
fstream fin;
fin.open("Map/" + map_name + "/Map.map");
if(!fin.is_open())
{
cerr << "Error! Couldn't open map\n";
return;
}
string MapName;
//Background parameters
float BgWidth;
float BgHeight;
string BgTexture;
//Terrain parameters
unsigned int TerrainWidth;
unsigned int TerrainHeight;
float TileSize;
//Minden egyรฉb
float lTilePos;//a legszรฉlsล baloldali tile pozรญciรณja
while(!fin.eof())
{
string Tmp;
fin >> Tmp;
if(Tmp == "MapName")
{
LoadQuotedString(fin,MapName);
}
if(Tmp == "BgWidth")
{
fin >> BgWidth;
}
if(Tmp == "BgHeight")
{
fin >> BgHeight;
}
if(Tmp == "BgTexture")
{
LoadQuotedString(fin,BgTexture);
Background = new lRect(lmVector2D::NULL_VECTOR,BgWidth,BgHeight,lRect::UP,lColor(1.0,1.0,1.0,1.0),resource_manager.GetImage(content_directory + BgTexture));
}
if(Tmp == "TerrainWidth")
{
fin >> TerrainWidth;
}
if(Tmp == "TerrainHeight")
{
fin >> TerrainHeight;
Terrain = new lTerrain(TerrainWidth,TerrainHeight);
}
if(Tmp == "TileSize")
{
fin >> TileSize;
lTilePos = (Width - TileSize*TerrainWidth)/2.0;
}
if(Tmp == "{")
{
for(unsigned int i=0;i < TerrainHeight;i++)
{
for(unsigned int j=0;j < TerrainWidth;j++)
{
bool IsAvailable;
string Texture;
fin >> Tmp;
fin >> IsAvailable;
fin >> Tmp;
if(IsAvailable)
{LoadQuotedString(fin,Texture);}
fin >> Tmp;
lmVector2D tPosition(lTilePos + j*TileSize,Height - i*TileSize);
if(IsAvailable)
{
(*Terrain)[i][j] = new lTerrain::lTile(new lRect(tPosition,TileSize,TileSize,lRect::UP,lColor(1.0,1.0,1.0,1.0),resource_manager.GetImage(content_directory + Texture)));
}
else
{
(*Terrain)[i][j] = nullptr;
}
}
}
fin >> Tmp;
}
}
}
lMap::~lMap()
{
delete Background;
delete Terrain;
for(auto I = Objects.begin();I != Objects.end();I++)
{
delete *I;
}
for(auto I = Projectiles.begin();I != Projectiles.end();I++)
{
delete *I;
}
}
|
[
"[email protected]"
] | |
a6cd08299186b85acb825e9ac282670ccd4939c1
|
3be416326180500f45bc75961eef25993fa4920f
|
/Content3/02SoundSynthesis/3VanDenDoel/Bell.cpp
|
98ceb0c3a3415aac8c67ff13148f40eb6b284002
|
[] |
no_license
|
Salimlou/AudioAnecdotes
|
3526123767c7b97eedb9058ca77538bd731fe6a5
|
0a8a9b0d32e2217203107b5ad95bbda70179c84e
|
refs/heads/master
| 2021-01-16T20:40:03.909093 | 2007-04-23T04:27:27 | 2007-04-23T04:27:27 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,601 |
cpp
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <pablio.h>
/** Modal model, which is loaded from an .sy format text file.
@author Kees van den Doel ([email protected])
*/
/** Mode frequencies in Hertz. */
float *f;
/** Angular decay rates in Hertz. */
float *d;
/** Gains. a[p][k] is gain at point p for mode k. */
float *a;
/** Number of modes available. */
int nf;
/** Number of modes used. */
int nfUsed;
/** Number of points. */
int np;
/** Multiplies all frequencies. */
float fscale;
/** Multiplies all dampings. */
float dscale;
/** Multiplies all gains. */
float ascale;
/** Allocated arrays.
@param nf number of modes.
@param np number of locations.
*/
void allocateArrays(int nf, int np) {
f = new float[nf];
d = new float[nf];
a = new float[np*nf];
fscale = dscale = ascale = 1.f;
};
void readModes(FILE *fp) {
float dval;
int ival;
char s[256];
fscanf(fp, "%s\n", &s);
// s is now: "nactive_freq:"
fscanf(fp, "%d\n", &nfUsed);
//printf(":%s:\n",s);
fscanf(fp, "%s\n", &s); // n_freq:
fscanf(fp, "%d\n", &nf);
fscanf(fp, "%s\n", &s); // n_points:
fscanf(fp, "%d\n", &np);
fscanf(fp, "%s\n", &s); // f_scale:
fscanf(fp, "%f\n", &fscale);
fscanf(fp, "%s\n", &s); // d_scale:
fscanf(fp, "%f\n", &dscale);
fscanf(fp, "%s\n", &s); // a_scale:
fscanf(fp, "%f\n", &ascale);
allocateArrays(nf,np);
fscanf(fp, "%s\n", &s); // frequencies:
for(int i=0;i<nf;i++) {
fscanf(fp, "%f\n", &f[i]);
}
fscanf(fp, "%s\n", &s); // dampings:
for(int i=0;i<nf;i++) {
fscanf(fp, "%f\n", &d[i]);
}
fscanf(fp, "%s\n", &s); // amplitudes[point][freq]:
for(int p=0;p<np;p++) {
for(int i=0;i<nf;i++) {
fscanf(fp, "%f\n", &a[p*nf+i]);
}
}
fscanf(fp, "%s\n", &s); // END
};
/** Read the modes file in .sy format.
@param fn File name with modal data in .sy format.
*/
void readModesFile(char *fn) {
FILE *fp = fopen(fn, "r");
readModes(fp);
fclose(fp);
};
/** Vibration model of object, capable of playing sound.
@author Kees van den Doel ([email protected])
*/
/** Sampling rate in Hertz. */
float srate = 44100.f;
/** State of filters. */
float *yt_1, *yt_2;
/** The transfer function of a reson filter is H(z) = 1/(1-twoRCosTheta/z + R2/z*z). */
float *R2;
/** The transfer function of a reson filter is H(z) = 1/(1-twoRCosTheta/z + R2/z*z). */
float *twoRCosTheta;
/** Cached values. */
float *c_i;
/** Reson filter gain vector. */
float *ampR;
/** Compute gains of contact
*/
void computeLocation() {
for(int i=0;i<nf;i++) {
ampR[i] = ascale * c_i[i] * a[i];
}
}
/** Set state to non-vibrating.
*/
void clearHistory() {
for(int i=0;i<nf;i++) {
yt_1[i] = yt_2[i] = 0;
}
}
/** Allocate data.
@param nf number of modes.
@param np number of locations.
*/
void allocateData(int nf,int np) {
R2 = new float[nf];
twoRCosTheta = new float[nf];
yt_1 = new float[nf];
yt_2 = new float[nf];
c_i = new float[nf];
ampR = new float[nf];
clearHistory();
}
/** Compute the reson coefficients from the modal model parameters.
Cache values for location computation.
*/
void computeResonCoeff() {
for(int i=0;i<nf;i++) {
float tmp_r = (float)(exp(-dscale*d[i]/srate));
R2[i] = tmp_r*tmp_r;
twoRCosTheta[i] = (float)(2.*cos(2.*M_PI*fscale*f[i]/srate)*tmp_r);
c_i[i] = (float)(sin(2.*M_PI*fscale*f[i]/srate)*tmp_r);
}
}
/** Compute the filter coefficients used for real-time rendering
from the modal model parameters.
*/
void computeFilter() {
computeResonCoeff();
computeLocation();
}
/** Compute response through bank of modal filters.
@param output provided output buffer.
*/
void computeSoundBuffer(float *output, float *force, int nsamples) {
for(int k=0;k<nsamples;k++) {
output[k] = 0;
}
int nf = nfUsed;
for(int i=0;i<nf;i++) {
float tmp_twoRCosTheta = twoRCosTheta[i];
float tmp_R2 = R2[i];
float tmp_a = ampR[i];
float tmp_yt_1 = yt_1[i];
float tmp_yt_2 = yt_2[i];
for(int k=0;k<nsamples;k++) {
float ynew = tmp_twoRCosTheta * tmp_yt_1 - tmp_R2 * tmp_yt_2
+ tmp_a * force[k];
tmp_yt_2 = tmp_yt_1;
tmp_yt_1 = ynew;
output[k] += ynew;
}
yt_1[i] = tmp_yt_1;
yt_2[i] = tmp_yt_2;
}
}
int main(int argc, char* argv[])
{
int bufferSize = 4096;
float *buffer = new float[bufferSize];
if(argc != 2) {
printf("Usage: Bell bell4.sy\n");
return -1;
}
PABLIO_Stream *outStream;
OpenAudioStream(&outStream, srate, paFloat32, PABLIO_WRITE|PABLIO_MONO);
readModesFile(argv[1]);
printf("nactive_freq: %d\n",nfUsed);
printf("n_freq: %d\n",nf);
printf("n_points: %d\n",np);
printf("f_scale: %f\n",fscale);
printf("d_scale: %f\n",dscale);
printf("a_scale: %f\n",ascale);
printf("frequencies:\n");
for(int i=0;i<nf;i++) {
printf("%f\n",f[i]);
}
printf("dampings:\n");
for(int i=0;i<nf;i++) {
printf("%f\n",d[i]);
}
printf("amplitudes[point][freq]:\n");
for(int p=0;p<np;p++) {
for(int i=0;i<nf;i++) {
printf("%f\n",a[p*nf+i]);
}
}
allocateData(nf,np);
computeFilter();
float dur = .0002f; // 2 ms
int nsamples = (int)(srate * dur);
printf("nsamples: %d\n",nsamples);
float *cosForce = new float[bufferSize];
memset(cosForce, 0, bufferSize*sizeof(float));
for(int i=0;i<nsamples;i++) {
cosForce[i] = (float)(.5*(1.-cos(2*M_PI*(i+1)/(1+nsamples))));
}
int x;
while(true) {
computeSoundBuffer(buffer, cosForce, bufferSize);
memset(cosForce, 0, nsamples*sizeof(float));
for(int i=0;i<bufferSize;i++) {
buffer[i] /= nf;
// printf("%f\n",buffer[i]);
// XXX Realy should saturate...
if (buffer[i] > 1.0)
buffer[i] = 1.0;
if (buffer[i] < -1.0)
buffer[i] = -1.0;
}
WriteAudioStream(outStream, buffer, bufferSize);
}
CloseAudioStream(outStream);
return 0;
}
|
[
"howardg"
] |
howardg
|
9a43c540116c907437d5bde49be220011f9608c7
|
4a25372ebed03096119b66f2dfe6dbc14ec442ed
|
/labs/2014/bugaev.bogdan/3/src/export.cpp
|
177c7410294eb41e3de6ed37f220eb12857aa7a9
|
[] |
no_license
|
gumeniukcom/aptu-os
|
218af3df72960db4ecd211ddccb51a03064e9625
|
4f4013f3495fb5781cda4696dde2809703bb78d9
|
refs/heads/master
| 2021-05-30T16:35:47.182087 | 2014-12-19T07:07:56 | 2014-12-19T07:07:56 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,234 |
cpp
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "config.h"
#include "header.h"
#include "utils.h"
#include "page.h"
#include "file.h"
int main(int argc, char **argv)
{
Config config;
try {
config = init(argc, argv);
} catch (ConfigException const &e) {
std::cerr << e.message() << std::endl;
return EXIT_FAILURE;
}
if (argc != 4) {
std::cerr << "Illegal arguments" << std::endl;
return EXIT_FAILURE;
}
try {
Path path(argv[2]);
int currentFile = getHeaderSize(config);
for (size_t i = 0; i < path.list().size(); ++i) {
currentFile = findFileNumber(config, currentFile, path.list()[i]);
if (currentFile == -1) {
std::cerr << "Path doesn't exist" << std::endl;
return EXIT_FAILURE;
}
}
std::ofstream dst(argv[3], std::ofstream::binary);
if (!dst) {
std::cerr << "Couldn't open output file" << std::endl;
return EXIT_FAILURE;
}
Page page;
page.load(config, currentFile);
if (isDir(page)) {
std::cerr << "Invalid path" << std::endl;
return EXIT_FAILURE;
}
PageReader reader(page);
int fileSize = reader.step<int>(3).read<int>();
reader.step<time_t>();
int nameSize = reader.read<int>();
reader.step<char>(nameSize);
while (reader.canRead<char>() && fileSize) {
dst.put(reader.read<char>());
--fileSize;
}
currentFile = PageReader(page).step<int>(2).read<int>();
page.unload();
while (currentFile != -1) {
Page page;
page.load(config, currentFile);
PageReader reader(page);
reader.step<int>();
while (fileSize && reader.canRead<char>()) {
dst.put(reader.read<char>());
--fileSize;
}
currentFile = PageReader(page).read<int>();
page.unload();
}
} catch (Exception const &e) {
std::cerr << e.message() << std::endl;
return EXIT_FAILURE;
}
return 0;
}
|
[
"[email protected]"
] | |
8abf2dc09b17b0c4581f10b1bf99bff25f8a0d3d
|
3b9b4049a8e7d38b49e07bb752780b2f1d792851
|
/src/third_party/webrtc/test/fake_network_pipe.cc
|
19f1b5451c82c99bf3bb9b3a2e7c1a9eca00e3d2
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown",
"MS-LPL",
"LicenseRef-scancode-takuya-ooura"
] |
permissive
|
webosce/chromium53
|
f8e745e91363586aee9620c609aacf15b3261540
|
9171447efcf0bb393d41d1dc877c7c13c46d8e38
|
refs/heads/webosce
| 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 |
Apache-2.0
| 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null |
UTF-8
|
C++
| false | false | 7,076 |
cc
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/fake_network_pipe.h"
#include <assert.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include "webrtc/call.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
FakeNetworkPipe::FakeNetworkPipe(Clock* clock,
const FakeNetworkPipe::Config& config)
: FakeNetworkPipe(clock, config, 1) {}
FakeNetworkPipe::FakeNetworkPipe(Clock* clock,
const FakeNetworkPipe::Config& config,
uint64_t seed)
: clock_(clock),
packet_receiver_(NULL),
random_(seed),
config_(config),
dropped_packets_(0),
sent_packets_(0),
total_packet_delay_(0),
bursting_(false),
next_process_time_(clock_->TimeInMilliseconds()) {
double prob_loss = config.loss_percent / 100.0;
if (config_.avg_burst_loss_length == -1) {
// Uniform loss
prob_loss_bursting_ = prob_loss;
prob_start_bursting_ = prob_loss;
} else {
// Lose packets according to a gilbert-elliot model.
int avg_burst_loss_length = config.avg_burst_loss_length;
int min_avg_burst_loss_length = std::ceil(prob_loss / (1 - prob_loss));
RTC_CHECK_GT(avg_burst_loss_length, min_avg_burst_loss_length)
<< "For a total packet loss of " << config.loss_percent << "%% then"
<< " avg_burst_loss_length must be " << min_avg_burst_loss_length + 1
<< " or higher.";
prob_loss_bursting_ = (1.0 - 1.0 / avg_burst_loss_length);
prob_start_bursting_ = prob_loss / (1 - prob_loss) / avg_burst_loss_length;
}
}
FakeNetworkPipe::~FakeNetworkPipe() {
while (!capacity_link_.empty()) {
delete capacity_link_.front();
capacity_link_.pop();
}
while (!delay_link_.empty()) {
delete *delay_link_.begin();
delay_link_.erase(delay_link_.begin());
}
}
void FakeNetworkPipe::SetReceiver(PacketReceiver* receiver) {
packet_receiver_ = receiver;
}
void FakeNetworkPipe::SetConfig(const FakeNetworkPipe::Config& config) {
rtc::CritScope crit(&lock_);
config_ = config; // Shallow copy of the struct.
}
void FakeNetworkPipe::SendPacket(const uint8_t* data, size_t data_length) {
// A NULL packet_receiver_ means that this pipe will terminate the flow of
// packets.
if (packet_receiver_ == NULL)
return;
rtc::CritScope crit(&lock_);
if (config_.queue_length_packets > 0 &&
capacity_link_.size() >= config_.queue_length_packets) {
// Too many packet on the link, drop this one.
++dropped_packets_;
return;
}
int64_t time_now = clock_->TimeInMilliseconds();
// Delay introduced by the link capacity.
int64_t capacity_delay_ms = 0;
if (config_.link_capacity_kbps > 0)
capacity_delay_ms = data_length / (config_.link_capacity_kbps / 8);
int64_t network_start_time = time_now;
// Check if there already are packets on the link and change network start
// time forward if there is.
if (!capacity_link_.empty() &&
network_start_time < capacity_link_.back()->arrival_time())
network_start_time = capacity_link_.back()->arrival_time();
int64_t arrival_time = network_start_time + capacity_delay_ms;
NetworkPacket* packet = new NetworkPacket(data, data_length, time_now,
arrival_time);
capacity_link_.push(packet);
}
float FakeNetworkPipe::PercentageLoss() {
rtc::CritScope crit(&lock_);
if (sent_packets_ == 0)
return 0;
return static_cast<float>(dropped_packets_) /
(sent_packets_ + dropped_packets_);
}
int FakeNetworkPipe::AverageDelay() {
rtc::CritScope crit(&lock_);
if (sent_packets_ == 0)
return 0;
return static_cast<int>(total_packet_delay_ /
static_cast<int64_t>(sent_packets_));
}
void FakeNetworkPipe::Process() {
int64_t time_now = clock_->TimeInMilliseconds();
std::queue<NetworkPacket*> packets_to_deliver;
{
rtc::CritScope crit(&lock_);
// Check the capacity link first.
while (!capacity_link_.empty() &&
time_now >= capacity_link_.front()->arrival_time()) {
// Time to get this packet.
NetworkPacket* packet = capacity_link_.front();
capacity_link_.pop();
// Drop packets at an average rate of |config_.loss_percent| with
// and average loss burst length of |config_.avg_burst_loss_length|.
if ((bursting_ && random_.Rand<double>() < prob_loss_bursting_) ||
(!bursting_ && random_.Rand<double>() < prob_start_bursting_)) {
bursting_ = true;
delete packet;
continue;
} else {
bursting_ = false;
}
int arrival_time_jitter = random_.Gaussian(
config_.queue_delay_ms, config_.delay_standard_deviation_ms);
// If reordering is not allowed then adjust arrival_time_jitter
// to make sure all packets are sent in order.
if (!config_.allow_reordering && !delay_link_.empty() &&
packet->arrival_time() + arrival_time_jitter <
(*delay_link_.rbegin())->arrival_time()) {
arrival_time_jitter =
(*delay_link_.rbegin())->arrival_time() - packet->arrival_time();
}
packet->IncrementArrivalTime(arrival_time_jitter);
if (packet->arrival_time() < next_process_time_)
next_process_time_ = packet->arrival_time();
delay_link_.insert(packet);
}
// Check the extra delay queue.
while (!delay_link_.empty() &&
time_now >= (*delay_link_.begin())->arrival_time()) {
// Deliver this packet.
NetworkPacket* packet = *delay_link_.begin();
packets_to_deliver.push(packet);
delay_link_.erase(delay_link_.begin());
// |time_now| might be later than when the packet should have arrived, due
// to NetworkProcess being called too late. For stats, use the time it
// should have been on the link.
total_packet_delay_ += packet->arrival_time() - packet->send_time();
}
sent_packets_ += packets_to_deliver.size();
}
while (!packets_to_deliver.empty()) {
NetworkPacket* packet = packets_to_deliver.front();
packets_to_deliver.pop();
packet_receiver_->DeliverPacket(MediaType::ANY, packet->data(),
packet->data_length(), PacketTime());
delete packet;
}
}
int64_t FakeNetworkPipe::TimeUntilNextProcess() const {
rtc::CritScope crit(&lock_);
const int64_t kDefaultProcessIntervalMs = 30;
if (capacity_link_.empty() || delay_link_.empty())
return kDefaultProcessIntervalMs;
return std::max<int64_t>(next_process_time_ - clock_->TimeInMilliseconds(),
0);
}
} // namespace webrtc
|
[
"[email protected]"
] | |
657e84dfc1c2fc19e27c770cf7390e3d6f5b088a
|
4cdf44d425bd64feead9e371c06f99a575177176
|
/P1223.cpp
|
130d5dfb3209bf077db6bfc5dd6e8c8734fcadff
|
[] |
no_license
|
hmyuna/cpp
|
58fdd2340fc56cc346ceaa98fdd0c15023d2bc8f
|
14c4aeb006f7cac1cee9552daced487824f8c290
|
refs/heads/master
| 2020-04-24T22:51:55.385045 | 2019-05-08T14:22:19 | 2019-05-08T14:22:19 | 172,325,134 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 404 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
double sum;
int n;
long long t[1001];
double ans;
int main()
{
cin >> n;
int T___;
for (int i = 1; i <= n; i++)
{
cin >> T___;
t[i] = T___ * 1001 + i;
}
sort(t + 1, t + 1 + n);
for (int j = 1; j <= n; j++)
{
cout << t[j] % 1001 << " ";
sum += t[j] / 1001 * (n - j);
}
cout << endl;
ans = sum * 1.0 / n;
printf("%0.2lf", ans);
return 0;
}
|
[
"[email protected]"
] | |
f3493799fd9d4f1830ef7bf36ad885f913888623
|
25c2116e8ac5b5b262f9d912067c606719baa230
|
/src/exceptions/OutOfRangeException.cpp
|
5b32e28d0c422ea204fa2a41172a77a83c5db218
|
[] |
no_license
|
sergiorf/CityBuilderEngine
|
5a533fb9587bc251357328584a00cbd57afa4826
|
ed1a28798a7847b2583b80c184d4c3e58b0ec871
|
refs/heads/main
| 2023-07-16T14:31:39.117057 | 2021-01-05T18:00:54 | 2021-01-05T18:00:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 139 |
cpp
|
#include "OutOfRangeException.hpp"
OutOfRangeException::OutOfRangeException(const QString& message) :
EngineException(message)
{
}
|
[
"[email protected]"
] | |
3d24610962605f3ecd91a4a5e22dfe247812d525
|
89d2c6d55c8cf45b84d66a97db4ee2b6158a7b61
|
/CST276SRS02/EnumDateValidation/datevalidator.h
|
a2f0d8db9411195d1dc76eff8d5bccee6e980a79
|
[
"MIT"
] |
permissive
|
robotrobotrobotrobotrobot/CST276SRS02
|
43c37ab30ff358e1fd24fa4e7235d0bf3b5b197e
|
75eb84bedcc6fde19b69a64a26e8f3fff59687b4
|
refs/heads/master
| 2020-03-24T12:02:22.892647 | 2018-07-28T22:06:08 | 2018-07-28T22:06:08 | 142,701,783 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 438 |
h
|
//GoF Strategy
#ifndef DATEVALIDATORI18N_H
#define DATEVALIDATORI18N_H
#include "idatevalidator.h"
class DateValidatorI18N : public IDateValidator// DateValidatorI18N is the client of the strategy pattern
{
public:
enum class Format { YMD, DMY, MDY };
DateValidatorI18N() = default;
~DateValidatorI18N();
void operation();
bool is_good(std::string const date)const override;
private:
};
#endif // !DATEVALIDATORI18N_H
|
[
"[email protected]"
] | |
dea81256d0d6880ef66138c6063367fe09ad8803
|
5a60d60fca2c2b8b44d602aca7016afb625bc628
|
/aws-cpp-sdk-chime/include/aws/chime/model/RedactConversationMessageResult.h
|
e59e1e0dc4d60b78c81e2d84020e66ccf5db4d75
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
yuatpocketgems/aws-sdk-cpp
|
afaa0bb91b75082b63236cfc0126225c12771ed0
|
a0dcbc69c6000577ff0e8171de998ccdc2159c88
|
refs/heads/master
| 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null |
UTF-8
|
C++
| false | false | 814 |
h
|
๏ปฟ/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Chime
{
namespace Model
{
class RedactConversationMessageResult
{
public:
AWS_CHIME_API RedactConversationMessageResult();
AWS_CHIME_API RedactConversationMessageResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_CHIME_API RedactConversationMessageResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
};
} // namespace Model
} // namespace Chime
} // namespace Aws
|
[
"[email protected]"
] | |
e9cd7ce5258273b63ae99c62b0a17a51491bc64f
|
634b935923d7387cf1015126eb02853eba848bc8
|
/14.longest-common-prefix.cpp
|
214b32f25d5d2369c08fa1b47df181cefe5c1b6b
|
[] |
no_license
|
Chester-zZz/leetcode
|
2944c80ce891bc17c457fccb40eb66d87aba1574
|
477b43ec1365b6046181ae8bec2c22eac2fdc9d8
|
refs/heads/master
| 2020-04-27T01:58:13.537340 | 2019-03-15T10:52:37 | 2019-03-15T10:52:37 | 173,980,294 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,226 |
cpp
|
/*
* @lc app=leetcode id=14 lang=cpp
*
* [14] Longest Common Prefix
*
* https://leetcode.com/problems/longest-common-prefix/description/
*
* algorithms
* Easy (32.99%)
* Total Accepted: 411.3K
* Total Submissions: 1.2M
* Testcase Example: '["flower","flow","flight"]'
*
* Write a function to find the longest common prefix string amongst an array
* of strings.
*
* If there is no common prefix, return an empty string "".
*
* Example 1:
*
*
* Input: ["flower","flow","flight"]
* Output: "fl"
*
*
* Example 2:
*
*
* Input: ["dog","racecar","car"]
* Output: ""
* Explanation: There is no common prefix among the input strings.
*
*
* Note:
*
* All given inputs are in lowercase letters a-z.
*
*/
#include <string>
#include <vector>
class Solution {
public:
std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) {
return "";
}
for (int i = 0; i < strs[0].size(); ++i) {
for (int j = 1; j < strs.size(); ++j) {
if (i > strs[j].size() || strs[0][i] != strs[j][i]) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};
|
[
"[email protected]"
] | |
c2ed80c0cc212216029f37c8082dd50be133ac4d
|
6e786e8f4c229aeb0822c9cdffccf109d7a32d41
|
/Codeforces/318A.cpp
|
e5973589cd845be7cb9061c344ad34711aec98e5
|
[] |
no_license
|
rajatdiptabiswas/competitive-programming
|
337da9c86e0cfae7ed1b36fec9b6e225167edfcc
|
ed036e91b9516d8a29d1322db159d68462178d94
|
refs/heads/master
| 2021-06-10T08:59:40.296322 | 2021-04-17T06:51:18 | 2021-04-17T06:51:18 | 138,393,143 | 0 | 1 | null | 2019-10-26T19:53:33 | 2018-06-23T10:43:17 |
Python
|
UTF-8
|
C++
| false | false | 1,708 |
cpp
|
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <limits>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
#include <queue>
#include <deque>
#include <list>
#include <stack>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <bitset>
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define DEBUG(x) cout << #x << " = " << x << endl;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOR(i, j, k, in) for (int i = j; i < k; i += in)
#define RFOR(i, j, k, in) for (int i = j; i >= k; i -= in)
#define REP(i, j) FOR(i, 0, j, 1)
#define RREP(i, j) RFOR(i, j, 0, 1)
#define ALL(container) container.begin(), container.end()
#define RALL(container) container.end(), container.begin()
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define CONTAINS(container, x) (container.find(x) != container.end())
#define MAX(a, b) a = max(a, b)
#define MIN(a, b) a = min(a, b)
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
using namespace std;
int main(int argc, char const *argv[]) {
FASTIO;
int64 n, k;
cin >> n >> k;
int64 output;
if (k > ceil(1.0 * n / 2)) {
output = 2 * (k - ceil(1.0 * n / 2));
} else {
output = 2 * (k - 1) + 1;
}
cout << output << endl;
return 0;
}
|
[
"[email protected]"
] | |
0a93a0f3ec21a0547c65ce19faac3cac6daeb535
|
683bbeb782fb15c9f7ac7cc4577bc99b8d8269ba
|
/Problem52.cpp
|
0f650db3a2e48be993d1958d65dd76422a728a33
|
[] |
no_license
|
iojw/project-euler
|
68cd9e4d9135d1c6f7f92543d238cbfdaa8fe5fd
|
061c3573b5da3594be2a373ae129a5bb351ef019
|
refs/heads/master
| 2021-01-10T23:19:31.810371 | 2016-11-19T17:56:23 | 2016-11-19T17:56:23 | 70,623,160 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 892 |
cpp
|
/*It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string toString(int num){
stringstream ss;
ss<<num;
return ss.str();
}
bool isPerm(int num){
string a=toString(num);
string b=toString(num*2);
string c=toString(num*3);
string d=toString(num*4);
string e=toString(num*5);
string f=toString(num*6);
sort(a.begin(), a.end());
sort(b.begin(), b.end());
sort(c.begin(), c.end());
sort(d.begin(), d.end());
sort(e.begin(), e.end());
sort(f.begin(), f.end());
if (a==b&&b==c&&c==d&&d==e&&e==f)
return true;
else
return false;
}
int main(){
for (int i=1;;i++){
if (isPerm(i))
{cout<<i<<endl;break;}
}
return 0;
}
|
[
"[email protected]"
] | |
da8c023d8edbd6f0f87a1ac89e9b5331a97014b6
|
9cabdeb8dce5718e8f4f490f3684eba0eb1f2d2e
|
/src/script.h
|
2859eb668768fc037ab47618844871f540188a88
|
[
"MIT"
] |
permissive
|
wolfoxonly/woo
|
fcfe275007cb102fff10239b0f722264dbbd40e2
|
a5fb13575afe855b58915bd8e15cbffb9015e5e2
|
refs/heads/master
| 2020-03-09T17:00:57.668308 | 2018-05-13T15:21:17 | 2018-05-13T15:21:17 | 127,590,136 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 20,979 |
h
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Woochain developers
// Copyright (c) 2012-2017 The Woochain developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef H_BITCOIN_SCRIPT
#define H_BITCOIN_SCRIPT
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/variant.hpp>
#include "keystore.h"
#include "bignum.h"
typedef std::vector<unsigned char> valtype;
class CCoins;
class CTransaction;
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
// Threshold for nLockTime: below this value it is interpreted as block number,
// otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Signature hash types/flags */
enum
{
SIGHASH_ALL = 1,
SIGHASH_NONE = 2,
SIGHASH_SINGLE = 3,
SIGHASH_ANYONECANPAY = 0x80,
};
/** Script verification flags */
enum
{
SCRIPT_VERIFY_NONE = 0,
SCRIPT_VERIFY_P2SH = (1U << 0),
SCRIPT_VERIFY_STRICTENC = (1U << 1),
SCRIPT_VERIFY_NOCACHE = (1U << 2),
// Discourage use of NOPs reserved for upgrades (NOP1-10)
//
// Provided so that nodes can avoid accepting or mining transactions
// containing executed NOP's whose meaning may change after a soft-fork,
// thus rendering the script invalid; with this flag set executing
// discouraged NOPs fails the script. This verification flag will never be
// a mandatory flag applied to scripts in a block. NOPs that are not
// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 7),
// Verify CHECKLOCKTIMEVERIFY
//
// See BIP65 for details.
SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9),
};
enum txnouttype
{
TX_NONSTANDARD,
// 'standard' transaction types:
TX_PUBKEY,
TX_PUBKEYHASH,
TX_SCRIPTHASH,
TX_MULTISIG,
TX_NULL_DATA,
};
class CNoDestination {
public:
friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
};
/** A txout script template with a specific destination. It is either:
* * CNoDestination: no destination set
* * CKeyID: TX_PUBKEYHASH destination
* * CScriptID: TX_SCRIPTHASH destination
* A CTxDestination is the internal data type encoded in a CWoochainAddress
*/
typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
const char* GetTxnOutputType(txnouttype t);
/** Script opcodes */
enum opcodetype
{
// push value
OP_0 = 0x00,
OP_FALSE = OP_0,
OP_PUSHDATA1 = 0x4c,
OP_PUSHDATA2 = 0x4d,
OP_PUSHDATA4 = 0x4e,
OP_1NEGATE = 0x4f,
OP_RESERVED = 0x50,
OP_1 = 0x51,
OP_TRUE=OP_1,
OP_2 = 0x52,
OP_3 = 0x53,
OP_4 = 0x54,
OP_5 = 0x55,
OP_6 = 0x56,
OP_7 = 0x57,
OP_8 = 0x58,
OP_9 = 0x59,
OP_10 = 0x5a,
OP_11 = 0x5b,
OP_12 = 0x5c,
OP_13 = 0x5d,
OP_14 = 0x5e,
OP_15 = 0x5f,
OP_16 = 0x60,
// control
OP_NOP = 0x61,
OP_VER = 0x62,
OP_IF = 0x63,
OP_NOTIF = 0x64,
OP_VERIF = 0x65,
OP_VERNOTIF = 0x66,
OP_ELSE = 0x67,
OP_ENDIF = 0x68,
OP_VERIFY = 0x69,
OP_RETURN = 0x6a,
// stack ops
OP_TOALTSTACK = 0x6b,
OP_FROMALTSTACK = 0x6c,
OP_2DROP = 0x6d,
OP_2DUP = 0x6e,
OP_3DUP = 0x6f,
OP_2OVER = 0x70,
OP_2ROT = 0x71,
OP_2SWAP = 0x72,
OP_IFDUP = 0x73,
OP_DEPTH = 0x74,
OP_DROP = 0x75,
OP_DUP = 0x76,
OP_NIP = 0x77,
OP_OVER = 0x78,
OP_PICK = 0x79,
OP_ROLL = 0x7a,
OP_ROT = 0x7b,
OP_SWAP = 0x7c,
OP_TUCK = 0x7d,
// splice ops
OP_CAT = 0x7e,
OP_SUBSTR = 0x7f,
OP_LEFT = 0x80,
OP_RIGHT = 0x81,
OP_SIZE = 0x82,
// bit logic
OP_INVERT = 0x83,
OP_AND = 0x84,
OP_OR = 0x85,
OP_XOR = 0x86,
OP_EQUAL = 0x87,
OP_EQUALVERIFY = 0x88,
OP_RESERVED1 = 0x89,
OP_RESERVED2 = 0x8a,
// numeric
OP_1ADD = 0x8b,
OP_1SUB = 0x8c,
OP_2MUL = 0x8d,
OP_2DIV = 0x8e,
OP_NEGATE = 0x8f,
OP_ABS = 0x90,
OP_NOT = 0x91,
OP_0NOTEQUAL = 0x92,
OP_ADD = 0x93,
OP_SUB = 0x94,
OP_MUL = 0x95,
OP_DIV = 0x96,
OP_MOD = 0x97,
OP_LSHIFT = 0x98,
OP_RSHIFT = 0x99,
OP_BOOLAND = 0x9a,
OP_BOOLOR = 0x9b,
OP_NUMEQUAL = 0x9c,
OP_NUMEQUALVERIFY = 0x9d,
OP_NUMNOTEQUAL = 0x9e,
OP_LESSTHAN = 0x9f,
OP_GREATERTHAN = 0xa0,
OP_LESSTHANOREQUAL = 0xa1,
OP_GREATERTHANOREQUAL = 0xa2,
OP_MIN = 0xa3,
OP_MAX = 0xa4,
OP_WITHIN = 0xa5,
// crypto
OP_RIPEMD160 = 0xa6,
OP_SHA1 = 0xa7,
OP_SHA256 = 0xa8,
OP_HASH160 = 0xa9,
OP_HASH256 = 0xaa,
OP_CODESEPARATOR = 0xab,
OP_CHECKSIG = 0xac,
OP_CHECKSIGVERIFY = 0xad,
OP_CHECKMULTISIG = 0xae,
OP_CHECKMULTISIGVERIFY = 0xaf,
// expansion
OP_NOP1 = 0xb0,
OP_NOP2 = 0xb1,
OP_CHECKLOCKTIMEVERIFY = OP_NOP2,
OP_NOP3 = 0xb2,
OP_NOP4 = 0xb3,
OP_NOP5 = 0xb4,
OP_NOP6 = 0xb5,
OP_NOP7 = 0xb6,
OP_NOP8 = 0xb7,
OP_NOP9 = 0xb8,
OP_NOP10 = 0xb9,
// template matching params
OP_SMALLDATA = 0xf9,
OP_SMALLINTEGER = 0xfa,
OP_PUBKEYS = 0xfb,
OP_PUBKEYHASH = 0xfd,
OP_PUBKEY = 0xfe,
OP_INVALIDOPCODE = 0xff,
};
const char* GetOpName(opcodetype opcode);
inline std::string ValueString(const std::vector<unsigned char>& vch)
{
if (vch.size() <= 4)
return strprintf("%d", CBigNum(vch).getint());
else
return HexStr(vch);
}
inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
{
std::string str;
BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
{
if (!str.empty())
str += " ";
str += ValueString(vch);
}
return str;
}
/** Serialized script, used inside transaction inputs and outputs */
class CScript : public std::vector<unsigned char>
{
protected:
CScript& push_int64(int64 n)
{
if (n == -1 || (n >= 1 && n <= 16))
{
push_back(n + (OP_1 - 1));
}
else
{
CBigNum bn(n);
*this << bn.getvch();
}
return *this;
}
CScript& push_uint64(uint64 n)
{
if (n >= 1 && n <= 16)
{
push_back(n + (OP_1 - 1));
}
else
{
CBigNum bn(n);
*this << bn.getvch();
}
return *this;
}
public:
CScript() { }
CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
#ifndef _MSC_VER
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
#endif
CScript& operator+=(const CScript& b)
{
insert(end(), b.begin(), b.end());
return *this;
}
friend CScript operator+(const CScript& a, const CScript& b)
{
CScript ret = a;
ret += b;
return ret;
}
//explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
explicit CScript(signed char b) { operator<<(b); }
explicit CScript(short b) { operator<<(b); }
explicit CScript(int b) { operator<<(b); }
explicit CScript(long b) { operator<<(b); }
explicit CScript(int64 b) { operator<<(b); }
explicit CScript(unsigned char b) { operator<<(b); }
explicit CScript(unsigned int b) { operator<<(b); }
explicit CScript(unsigned short b) { operator<<(b); }
explicit CScript(unsigned long b) { operator<<(b); }
explicit CScript(uint64 b) { operator<<(b); }
explicit CScript(opcodetype b) { operator<<(b); }
explicit CScript(const uint256& b) { operator<<(b); }
explicit CScript(const CBigNum& b) { operator<<(b); }
explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
//CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
CScript& operator<<(signed char b) { return push_int64(b); }
CScript& operator<<(short b) { return push_int64(b); }
CScript& operator<<(int b) { return push_int64(b); }
CScript& operator<<(long b) { return push_int64(b); }
CScript& operator<<(int64 b) { return push_int64(b); }
CScript& operator<<(unsigned char b) { return push_uint64(b); }
CScript& operator<<(unsigned int b) { return push_uint64(b); }
CScript& operator<<(unsigned short b) { return push_uint64(b); }
CScript& operator<<(unsigned long b) { return push_uint64(b); }
CScript& operator<<(uint64 b) { return push_uint64(b); }
CScript& operator<<(opcodetype opcode)
{
if (opcode < 0 || opcode > 0xff)
throw std::runtime_error("CScript::operator<<() : invalid opcode");
insert(end(), (unsigned char)opcode);
return *this;
}
CScript& operator<<(const uint160& b)
{
insert(end(), sizeof(b));
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
return *this;
}
CScript& operator<<(const uint256& b)
{
insert(end(), sizeof(b));
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
return *this;
}
CScript& operator<<(const CPubKey& key)
{
std::vector<unsigned char> vchKey = key.Raw();
return (*this) << vchKey;
}
CScript& operator<<(const CBigNum& b)
{
*this << b.getvch();
return *this;
}
CScript& operator<<(const std::vector<unsigned char>& b)
{
if (b.size() < OP_PUSHDATA1)
{
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xff)
{
insert(end(), OP_PUSHDATA1);
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xffff)
{
insert(end(), OP_PUSHDATA2);
unsigned short nSize = b.size();
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
}
else
{
insert(end(), OP_PUSHDATA4);
unsigned int nSize = b.size();
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
}
insert(end(), b.begin(), b.end());
return *this;
}
CScript& operator<<(const CScript& b)
{
// I'm not sure if this should push the script or concatenate scripts.
// If there's ever a use for pushing a script onto a script, delete this member fn
assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
return *this;
}
bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
{
// Wrapper so it can be called with either iterator or const_iterator
const_iterator pc2 = pc;
bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
pc = begin() + (pc2 - begin());
return fRet;
}
bool GetOp(iterator& pc, opcodetype& opcodeRet)
{
const_iterator pc2 = pc;
bool fRet = GetOp2(pc2, opcodeRet, NULL);
pc = begin() + (pc2 - begin());
return fRet;
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
{
return GetOp2(pc, opcodeRet, &vchRet);
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
{
return GetOp2(pc, opcodeRet, NULL);
}
bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
{
opcodeRet = OP_INVALIDOPCODE;
if (pvchRet)
pvchRet->clear();
if (pc >= end())
return false;
// Read instruction
if (end() - pc < 1)
return false;
unsigned int opcode = *pc++;
// Immediate operand
if (opcode <= OP_PUSHDATA4)
{
unsigned int nSize = 0;
if (opcode < OP_PUSHDATA1)
{
nSize = opcode;
}
else if (opcode == OP_PUSHDATA1)
{
if (end() - pc < 1)
return false;
nSize = *pc++;
}
else if (opcode == OP_PUSHDATA2)
{
if (end() - pc < 2)
return false;
nSize = 0;
memcpy(&nSize, &pc[0], 2);
pc += 2;
}
else if (opcode == OP_PUSHDATA4)
{
if (end() - pc < 4)
return false;
memcpy(&nSize, &pc[0], 4);
pc += 4;
}
if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
return false;
if (pvchRet)
pvchRet->assign(pc, pc + nSize);
pc += nSize;
}
opcodeRet = (opcodetype)opcode;
return true;
}
// Encode/decode small integers:
static int DecodeOP_N(opcodetype opcode)
{
if (opcode == OP_0)
return 0;
assert(opcode >= OP_1 && opcode <= OP_16);
return (int)opcode - (int)(OP_1 - 1);
}
static opcodetype EncodeOP_N(int n)
{
assert(n >= 0 && n <= 16);
if (n == 0)
return OP_0;
return (opcodetype)(OP_1+n-1);
}
int FindAndDelete(const CScript& b)
{
int nFound = 0;
if (b.empty())
return nFound;
iterator pc = begin();
opcodetype opcode;
do
{
while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
{
erase(pc, pc + b.size());
++nFound;
}
}
while (GetOp(pc, opcode));
return nFound;
}
int Find(opcodetype op) const
{
int nFound = 0;
opcodetype opcode;
for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
if (opcode == op)
++nFound;
return nFound;
}
// Pre-version-0.6, Woochain always counted CHECKMULTISIGs
// as 20 sigops. With pay-to-script-hash, that changed:
// CHECKMULTISIGs serialized in scriptSigs are
// counted more accurately, assuming they are of the form
// ... OP_N CHECKMULTISIG ...
unsigned int GetSigOpCount(bool fAccurate) const;
// Accurately count sigOps, including sigOps in
// pay-to-script-hash transactions:
unsigned int GetSigOpCount(const CScript& scriptSig) const;
bool IsPayToScriptHash() const;
// Called by CTransaction::IsStandard
bool IsPushOnly() const
{
const_iterator pc = begin();
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
if (opcode > OP_16)
return false;
}
return true;
}
void SetDestination(const CTxDestination& address);
void SetMultisig(int nRequired, const std::vector<CKey>& keys);
void PrintHex() const
{
printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
}
std::string ToString(bool fShort=false) const
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
const_iterator pc = begin();
while (pc < end())
{
if (!str.empty())
str += " ";
if (!GetOp(pc, opcode, vch))
{
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4)
str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
else
str += GetOpName(opcode);
}
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
CScriptID GetID() const
{
return CScriptID(Hash160(*this));
}
};
/** Compact serializer for scripts.
*
* It detects common cases and encodes them much more efficiently.
* 3 special cases are defined:
* * Pay to pubkey hash (encoded as 21 bytes)
* * Pay to script hash (encoded as 21 bytes)
* * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
*
* Other scripts up to 121 bytes require 1 byte + script length. Above
* that, scripts up to 16505 bytes require 2 bytes + script length.
*/
class CScriptCompressor
{
private:
// make this static for now (there are only 6 special scripts defined)
// this can potentially be extended together with a new nVersion for
// transactions, in which case this value becomes dependent on nVersion
// and nHeight of the enclosing transaction.
static const unsigned int nSpecialScripts = 6;
CScript &script;
protected:
// These check for scripts for which a special case with a shorter encoding is defined.
// They are implemented separately from the CScript test, as these test for exact byte
// sequence correspondences, and are more strict. For example, IsToPubKey also verifies
// whether the public key is valid (as invalid ones cannot be represented in compressed
// form).
bool IsToKeyID(CKeyID &hash) const;
bool IsToScriptID(CScriptID &hash) const;
bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
bool Compress(std::vector<unsigned char> &out) const;
unsigned int GetSpecialSize(unsigned int nSize) const;
bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
public:
CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
unsigned int GetSerializeSize(int nType, int nVersion) const {
std::vector<unsigned char> compr;
if (Compress(compr))
return compr.size();
unsigned int nSize = script.size() + nSpecialScripts;
return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
std::vector<unsigned char> compr;
if (Compress(compr)) {
s << CFlatData(&compr[0], &compr[compr.size()]);
return;
}
unsigned int nSize = script.size() + nSpecialScripts;
s << VARINT(nSize);
s << CFlatData(&script[0], &script[script.size()]);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nSize = 0;
s >> VARINT(nSize);
if (nSize < nSpecialScripts) {
std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
Decompress(nSize, vch);
return;
}
nSize -= nSpecialScripts;
script.resize(nSize);
s >> REF(CFlatData(&script[0], &script[script.size()]));
}
};
bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
// Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
// combine them intelligently and return the result.
CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
#endif
|
[
"[email protected]"
] | |
a8300654aae2da366b3244f2b6c6cd2705503c0f
|
47ff8543c73dab22c7854d9571dfc8d5f467ee8c
|
/BOJ/10869/10869.cpp
|
52fdd6fcfbcafcab18ec10e697f2c7de6e01908f
|
[] |
no_license
|
eldsg/BOJ
|
4bb0c93dc60783da151e685530fa9a511df3a141
|
6bd15e36d69ce1fcf208d193d5e9067de9bb405e
|
refs/heads/master
| 2020-04-16T02:18:55.808362 | 2017-11-28T11:02:37 | 2017-11-28T11:02:37 | 55,879,791 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 139 |
cpp
|
#include<stdio.h>
int main(){
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n%d\n%d\n%d\n%d\n", a+b, a-b, a*b, a/b, a%b);
}
|
[
"[email protected]"
] | |
73f2252b39c62966983542e1e8add799ab9c20cf
|
11cdcef2a97ec018d29307ccd23821bee875d9fe
|
/src/Shader.cpp
|
4df3bc54c814ac3c6810e6264532dd7f86bb8038
|
[] |
no_license
|
alepmaros/learnopengl-tutorial
|
6d9e7b4ec4680bb0c0529a3a162063ea5faca41d
|
8e4f4b93fe7117d167511cf2afcb8ba5bf4d136e
|
refs/heads/master
| 2021-03-24T09:56:48.554304 | 2018-01-24T17:18:58 | 2018-01-24T17:18:58 | 118,038,941 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,446 |
cpp
|
#include <Shader.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
Shader::Shader(const char* vertexPath, const char* fragmentPath)
{
// 1. retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try
{
// open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// close file handlers
vShaderFile.close();
fShaderFile.close();
// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char * fShaderCode = fragmentCode.c_str();
// 2. compile shaders
unsigned int vertex, fragment;
int success;
char infoLog[512];
// vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// activate the shader
// ------------------------------------------------------------------------
void Shader::use()
{
glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void Shader::setBool(const std::string &name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void Shader::setInt(const std::string &name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void Shader::setFloat(const std::string &name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
void Shader::setMat4(const std::string &name, glm::mat4 &value) const
{
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, glm::value_ptr(value));
}
void Shader::setVec3(const std::string &name, const glm::vec3 &value) const
{
glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void Shader::setVec3(const std::string &name, float x, float y, float z) const
{
glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void Shader::checkCompileErrors(unsigned int shader, std::string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
}
|
[
"[email protected]"
] | |
f40d7f7089c497b86bad9fefc1cfbcdef638fd76
|
fb27e2874b1bfb8fbc0ef9471671c3db6f42ed72
|
/353/1.cpp
|
2532026cb2885a7b791f5d69c9a534b94d6739df
|
[] |
no_license
|
2hanson/codeforces
|
d30911988bebc068285b2c5cab903bb6042058ec
|
d593c70a3e81a88739d138f8336b2ba523a0b768
|
refs/heads/master
| 2016-09-08T05:05:51.556546 | 2013-11-11T09:30:20 | 2013-11-11T09:30:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 552 |
cpp
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n;
bool flag = false;
vector<int> a(n+1, 0);
vector<int> b(n+1, 0);
for (int i = 1; i <= n; ++i) {
cin>>a[i]>>b[i];
if ((a[i]&1) ^ (b[i]&1)) {
flag = true;
}
a[0] += a[i];
b[0] += b[i];
}
if (!(a[0]&1) && !(b[0]&1)) {
cout<<0<<endl;
}
else if (!(a[0]&1) ^ !(b[0]&1)) {
cout<<-1<<endl;
}
else {
cout<<(flag?1:-1)<<endl;
}
return 0;
}
|
[
"[email protected]"
] | |
ffa93e255923a804ccac3f8f63d14692b65407b0
|
81bb77804b2481a92c0d48ad2f76e5b79d29e9ec
|
/src/test/libtestutils/Common.h
|
42d43de544a29691554963b09659bd8e9c6f4cf1
|
[
"MIT"
] |
permissive
|
AndrewJEON/qtum
|
a5216a67c25e818b11266366f37d0b7bcf5a573f
|
5373115c4550a9dbd99f360dd50cc4f67722dc91
|
refs/heads/master
| 2021-06-11T16:50:00.126511 | 2017-03-14T17:12:40 | 2017-03-14T17:12:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,257 |
h
|
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Common.h
* @author Marek Kotewicz <[email protected]>
* @date 2015
*/
#pragma once
#include <string>
// #include <json/json.h>
#include <libdevcore/Log.h>
namespace dev
{
namespace test
{
struct TestChannel: public LogChannel { static const char* name(); };
#define ctest dev::LogOutputStream<dev::test::TestChannel, true>()
std::string getTestPath();
int randomNumber();
// Json::Value loadJsonFromFile(std::string const& _path);
std::string toTestFilePath(std::string const& _filename);
std::string getFolder(std::string const& _file);
std::string getRandomPath();
}
}
|
[
"[email protected]"
] | |
7c69aa1fcec32405f5be56530980d285edef5f26
|
1a29e3fc23318be40f27339a749bbc3bdc59c0c3
|
/kattis/a4p8nf/a.cpp
|
bbc30e752776ad895c6a91be354828e2fab729da
|
[] |
no_license
|
wdzeng/cp-solutions
|
6c2ac554f6d291774929bc6ad612c4c2e3966c9f
|
8d39fcbda812a1db7e03988654cd20042cf4f854
|
refs/heads/master
| 2023-03-23T17:23:08.809526 | 2020-12-05T00:29:21 | 2020-12-05T00:29:21 | 177,706,525 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 809 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define x first
#define y second
#define all(v) v.begin(), v.end()
#define ms(v) memset(v, 0, sizeof(v))
#define mss(v) memset(v, -1, sizeof(v))
#define len(v) int(v.size())
#ifdef hy
#define fastio()
#define debug(a) cerr << #a << ": " << a << endl
#else
#define endl '\n'
#define fastio() cin.tie(0), ios::sync_with_stdio(0)
#define debug(a)
#endif
int main() {
fastio();
int a, b, c, d; cin >> a >> b >> c >> d;
for(int i=0; i<3; i++) {
int v; cin >> v;
v--;
int ok1 = (v%(a+b)) < a;
int ok2 = (v%(c+d)) < c;
if(ok1 && ok2) cout << "both" << endl;
else if(ok1 || ok2) cout << "one" << endl;
else cout << "none" << endl;
}
return 0;
}
|
[
"[email protected]"
] | |
057c060bea2a88b45e19a3e4ea9b25308d9390ec
|
d0bd0ba07fd5b674ed89dc8fe33069839436c2d6
|
/triform2/src/read_files.cpp
|
987c4bc462d3b8420c2171c27bec40ed0365d4f8
|
[] |
no_license
|
endrebak/triform2
|
6cca56f69df9235b8fdb324e36cd1672d1713c44
|
83ced8b6bde94520b4251c48129211fc727a94dc
|
refs/heads/master
| 2020-04-09T08:34:47.256910 | 2019-01-16T10:00:04 | 2019-01-16T10:00:04 | 60,792,596 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,796 |
cpp
|
#include <iostream>
#include <algorithm>
#include <fstream>
#include <map>
#include <vector>
#include <string>
#include <vector>
#include <iterator>
#include <math.h>
typedef std::vector<uint32_t> intvec;
typedef std::pair <std::string, char> key;
typedef std::map<key, intvec> genome_map;
struct interval { uint32_t start; uint32_t end; };
typedef std::vector<interval> interval_vector;
typedef std::map<key, interval_vector> genome_intervals;
uint32_t compare_by_start_end_(const interval lhs, const interval rhs){
if (lhs.start < rhs.start){
return 1;
} else if (rhs.start < lhs.start){
return 0;
} else if (lhs.end < rhs.end){
return 1;
} else {
return 0;
};
}
uint32_t start_end_equal_(const interval lhs, const interval rhs){
if ((lhs.start == rhs.start) && (lhs.end == rhs.end)){
return 1;
} else {
return 0;
}
}
genome_map intervals_to_points(genome_intervals genome, uint32_t drop_duplicates, uint32_t read_width) {
genome_intervals::iterator it;
uint32_t i = 0;
key chrom_strand;
interval_vector intervals;
genome_map genome_tags;
uint32_t gap = 0;
uint32_t start = 0;
uint32_t end = 0;
uint32_t width = 0;
it = genome.begin();
while(it != genome.end()){
chrom_strand = it->first;
intervals = it->second;
if (drop_duplicates){
std::sort(intervals.begin(), intervals.end(), compare_by_start_end_);
intervals.erase(unique(intervals.begin(), intervals.end(), start_end_equal_), intervals.end());
}
// df.Start += 1
// width = df.End - df.Start
// gaps = np.array(np.floor((read_width - width) / 2), dtype=np.long)
// df.Start = df.Start - gaps - 1
// df.End = df.Start + width + (2 * gaps)
// return df
i = 0;
for (i = 0; i < intervals.size(); i++){
start = intervals[i].start + 1;
width = (intervals[i].end - (start));
gap = floor((read_width - width)/2);
start = start - gap - 1;
end = start + width + gap + gap;
genome_tags[chrom_strand].push_back(start);
genome_tags[chrom_strand].push_back(end);
}
genome.erase(chrom_strand);
it++;
}
return genome_tags;
}
genome_map read_bed(char const* fileName, uint32_t drop_duplicates, uint32_t read_width)
{
std::ifstream file(fileName);
std::string chromosome;
std::string junk;
uint32_t start;
uint32_t end;
char strand;
key chrom_strand;
interval _interval;
interval_vector intervals;
genome_intervals genome;
while(file >> chromosome >> start >> end >> junk >> junk >> strand)
{
chrom_strand = std::make_pair(chromosome, strand);
_interval = {start, end - 1};
genome[chrom_strand].push_back(_interval);
}
return intervals_to_points(genome, drop_duplicates, read_width);
}
genome_map read_bedpe(char const* fileName, uint32_t drop_duplicates, uint32_t read_width)
{
std::ifstream file(fileName);
std::string chromosome;
std::string junk;
uint32_t start;
uint32_t end;
char strand;
key chrom_strand;
interval _interval;
interval_vector intervals;
genome_intervals genome;
while(file >> chromosome >> start >> junk >> junk >> junk >> end >> junk >> junk >> strand >> junk)
{
chrom_strand = std::make_pair(chromosome, strand);
_interval = {start, end - 1};
genome[chrom_strand].push_back(_interval);
}
return intervals_to_points(genome, drop_duplicates, read_width);
}
#include "gzstream.h"
genome_map read_bed_gz(char const* fileName, uint32_t drop_duplicates, uint32_t read_width)
{
igzstream in(fileName);
std::string chromosome;
std::string junk;
uint32_t start;
uint32_t end;
char strand;
key chrom_strand;
interval _interval;
// intvec tags;
interval_vector intervals;
genome_intervals genome;
while(in >> chromosome >> start >> end >> junk >> junk >> strand)
{
chrom_strand = std::make_pair(chromosome, strand);
_interval = {start, end - 1};
genome[chrom_strand].push_back(_interval);
}
return intervals_to_points(genome, drop_duplicates, read_width);
}
genome_map read_bedpe_gz(char const* fileName, uint32_t drop_duplicates, uint32_t read_width)
{
igzstream in(fileName);
std::string chromosome;
std::string junk;
uint32_t start;
uint32_t end;
char strand;
key chrom_strand;
interval _interval;
interval_vector intervals;
genome_intervals genome;
while(in >> chromosome >> start >> junk >> junk >> junk >> end >> junk >> junk >> strand >> junk)
{
chrom_strand = std::make_pair(chromosome, strand);
_interval = {start, end - 1};
genome[chrom_strand].push_back(_interval);
}
return intervals_to_points(genome, drop_duplicates, read_width);
}
|
[
"[email protected]"
] | |
ba144f9bcaa147dfbe314ec6d12b5c2b4441949b
|
fbc5d18001045ad7468c08380ab37db3477bc2b2
|
/client/levels/levelwidget.cpp
|
a0ab1b24e87b6f44fffbe14a51bf224457627ded
|
[] |
no_license
|
turenkoaa/seaBattle
|
1c0fd215983a4c9f0ee846660beaad2177aff8d6
|
3e731488b0825e28841d58dc01dfcd7345f0291c
|
refs/heads/master
| 2020-06-16T07:21:54.934986 | 2016-11-30T23:06:18 | 2016-11-30T23:06:18 | 75,234,763 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 398 |
cpp
|
#include "levelwidget.h"
#include "ui_levelwidget.h"
LevelWidget::LevelWidget(QWidget *parent) :
//QWidget(parent),
AbstractWidget(parent),
ui(new Ui::LevelWidget)
{
ui->setupUi(this);
easy=ui->easyButton;
veryEasy=ui->veryEasyButton;
medium=ui->mediumButton;
hard=ui->hardButton;
veryHard=ui->veryHardButton;
}
LevelWidget::~LevelWidget()
{
delete ui;
}
|
[
"[email protected]"
] | |
d85e94d9b7b6c0c6b572ef81ce45bce2c9dcf45f
|
3a04465af3de9ecc58711140a825947bb603df3c
|
/Undaunted/GroupList.h
|
ed4a614e388ec806928bb8f0c7bc39edcb966921
|
[
"MIT"
] |
permissive
|
clayne/Undaunted
|
59d77ec265209cf3d0ffc3b79eebac6ac18e81b4
|
76515249be217e865eae05b1656b3aeb32283fdc
|
refs/heads/master
| 2023-01-12T08:19:59.253760 | 2022-11-25T07:55:49 | 2022-11-25T07:55:49 | 279,496,032 | 0 | 0 |
MIT
| 2020-07-14T05:57:15 | 2020-07-14T05:57:15 | null |
UTF-8
|
C++
| false | false | 628 |
h
|
#include "SKSELink.h"
#include "UnStringList.h"
namespace Undaunted
{
#ifndef GroupListdef
#define GroupListdef
class GroupMember {
public:
UInt32 FormId;
std::string BountyType;
TESObjectREFR* objectRef;
BSFixedString ModelFilepath;
int IsComplete();
bool isComplete = false;
void PreBounty();
void PostBounty();
};
class GroupList {
public:
std::string questText;
GroupMember* data;
UInt32 minLevel;
UInt32 maxLevel;
int length;
UnStringlist Tags;
GroupList* AddItem(GroupMember item);
GroupList* SwapItem(int first, int second);
void SetGroupMemberComplete(UInt32 id);
};
#endif
}
|
[
"[email protected]"
] | |
5d4e61782daf5c43bc9ffb795f93764b292e5188
|
5cd40f362b26e4e20d62cad705ffec64bdb4d480
|
/PETCTCOSEG/optnet_vce_lib/optnet/_utils/timer.hxx
|
62a65d3715b2426ab0b1766e9949b66659391668
|
[] |
no_license
|
maxwell-zhou/PETCTCOSEGExtension
|
4fc0d728a04bcf4088c842b14d2dc0f97dc2d045
|
f9592fde632ded9403e33e1f175d6a5a0842c480
|
refs/heads/master
| 2021-01-20T09:54:39.019251 | 2017-01-18T16:26:13 | 2017-01-18T16:26:13 | 78,767,668 | 3 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,113 |
hxx
|
/*
==========================================================================
|
| $Id: timer.hxx 21 2005-01-14 15:52:31Z kangli $
|
| Written by Kang Li <[email protected]>
| Department of Electrical and Computer Engineering
| Carnegie Mellon University
|
==========================================================================
| This file is a part of the OptimalNet library.
==========================================================================
| Copyright (c) 2004-2005 Kang Li <[email protected]>. All Rights Reserved.
|
| This software is supplied under the terms of a license agreement or
| nondisclosure agreement with the author and may not be copied or
| disclosed except in accordance with the terms of that agreement.
==========================================================================
*/
#ifndef ___TIMER_HXX___
# define ___TIMER_HXX___
# if defined(_MSC_VER) && (_MSC_VER > 1000)
# pragma once
# endif
# include <optnet/config.h>
# if defined(__OPTNET_OS_WINNT__)
# include <windows.h>
# else
# include <ctime>
# endif
/// @namespace optnet
namespace optnet {
/// @namespace optnet::utils
/// @brief The namespace that contains utility classes and funtions.
namespace utils {
# if defined(__OPTNET_OS_WINNT__)
///////////////////////////////////////////////////////////////////////////
/// @class timer
/// @brief Simple timer class for measuring elapsed time.
///
/// Under Windows, this class uses the Win32 high-resolution timing APIs:
/// QueryPerformanceFrequency() and QueryPerformanceCounter(). Under the
/// other platforms, this class use the C Standard Library clock()
/// function.
///////////////////////////////////////////////////////////////////////////
class timer
{
public:
///////////////////////////////////////////////////////////////////////
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
timer()
{
LARGE_INTEGER cfreq;
// Set the clock frequency if it is not yet set.
QueryPerformanceFrequency(&cfreq);
m_cfreq = (double)cfreq.QuadPart;
// Get the current value of the high-res performance counter.
QueryPerformanceCounter(&m_start);
}
///////////////////////////////////////////////////////////////////////
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
void restart()
{
// Get the current value of the high-res performance counter.
QueryPerformanceCounter(&m_start);
}
///////////////////////////////////////////////////////////////////////
/// Returns elapsed time since the timer is created or restarted.
///
/// @return (double) Elapsed time in seconds.
///
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
double elapsed() const
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return double(now.QuadPart - m_start.QuadPart) / m_cfreq;
}
private:
// Frequency setting is based on the hardware clock that does not
// change between calling, so set this one only once.
DOUBLE m_cfreq;
// The starting time stored as a LARGE_INTEGER.
LARGE_INTEGER m_start;
};
# else // !__OPTNET_OS_WINNT__
///////////////////////////////////////////////////////////////////////////
/// @class timer
/// @brief Simple timer class for measuring elapsed time.
///
/// Under Windows, this class uses the Win32 high-resolution timing APIs:
/// QueryPerformanceFrequency() and QueryPerformanceCounter(). Under the
/// other platforms, this class use the C Standard Library clock()
/// function.
///////////////////////////////////////////////////////////////////////////
class timer
{
public:
///////////////////////////////////////////////////////////////////////
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
timer() { m_start = clock(); }
///////////////////////////////////////////////////////////////////////
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
void restart() { m_start = clock(); }
///////////////////////////////////////////////////////////////////////
/// Returns elapsed time since the timer is created or restarted.
///
/// @return (double) Elapsed time in seconds.
///
/// @post elapsed()==0
///////////////////////////////////////////////////////////////////////
double elapsed() const
{
return double(clock() - m_start) / CLOCKS_PER_SEC;
}
private:
// The starting time stored as a clock_t.
clock_t m_start;
};
# endif // __OPTNET_OS_WINNT__
} // namespace
} // namespace
#endif
|
[
"max@max-VirtualBox"
] |
max@max-VirtualBox
|
91b809e273243eeb5d0429b0b87af4bb1c0ef35e
|
be0401d72443dd37f8be2632ac32e1c5c0333499
|
/lib/Importer/TFLiteModelLoader.cpp
|
6831541c6e184eb5ae35f5a4925678add2df7a11
|
[
"Apache-2.0"
] |
permissive
|
842974287/glow
|
5c797f5d37a8b2b179c45689a2c5db09402c4f4f
|
7d77eb9a1c00dbba77321f62ad9c9078beb2b725
|
refs/heads/master
| 2023-06-06T09:49:19.753708 | 2020-10-08T07:43:55 | 2020-10-08T07:45:04 | 299,778,323 | 0 | 0 |
Apache-2.0
| 2020-09-30T01:25:13 | 2020-09-30T01:25:13 | null |
UTF-8
|
C++
| false | false | 87,687 |
cpp
|
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/Importer/TFLiteModelLoader.h"
#include "glow/Base/Tensor.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/Nodes.h"
#include "glow/Importer/CommonOperatorLoader.h"
#include "glow/Support/Support.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace glow;
using llvm::cast;
namespace {
llvm::cl::OptionCategory
tfliteModelLoaderCat("TensorFlowLite Model Loader Options");
llvm::cl::opt<bool> tfliteUint8ToInt8Opt(
"tflite-uint8-to-int8",
llvm::cl::desc("TensorFlowLite loader option to convert the model from "
"UINT8 data type to INT8 data type."),
llvm::cl::init(true), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
llvm::cl::opt<bool> tfliteFloatInputsOpt(
"tflite-float-inputs",
llvm::cl::desc("TensorFlowLite loader option to replace the quantized "
"inputs with floating point inputs."),
llvm::cl::init(false), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
llvm::cl::opt<bool> tfliteFloatOutputsOpt(
"tflite-float-outputs",
llvm::cl::desc("TensorFlowLite loader option to replace the quantized "
"outputs with floating point outputs."),
llvm::cl::init(false), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
llvm::cl::opt<bool> tfliteFloatSoftmaxOpt(
"tflite-float-softmax",
llvm::cl::desc("TensorFlowLite loader option to replace a quantized Softmax"
"with a floating point Softmax."),
llvm::cl::init(true), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
llvm::cl::opt<float> tfliteBiasScaleCheckMaxErrorOpt(
"tflite-bias-scale-check-max-error",
llvm::cl::desc(
"TensorFlowLite mandates that for quantized operators like Conv2D the "
"bias quantization parameter biasScale = inputScale * weightsScale but "
"some pre-quantized models do not EXACTLY satisfy this relation but "
"with very small relative errors (around 1e-8). Hence we allow a "
"tolerance of 1e-6 which, if satisfied, then we adjust the bias to "
"conform to the restriction."),
llvm::cl::init(1e-6), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
llvm::cl::opt<bool> tfliteBiasScaleCheckThrowErrorOpt(
"tflite-bias-scale-check-throw-error",
llvm::cl::desc(
"TensorFlowLite mandates that for quantized operators like Conv2D the "
"bias quantization parameter biasScale = inputScale * weightsScale. If "
"this contraint is not met within the given tolerance then an error "
"will be thrown if this option is enabled."),
llvm::cl::init(false), llvm::cl::Optional,
llvm::cl::cat(tfliteModelLoaderCat));
/// Function to read a TensorFlowLite model from the file \p modelFilename into
/// the data buffer \p modelData provided by the caller. The \p modelData buffer
/// is allocated and initialized by this function but the caller must ensure its
/// existence through the graph loading process. \returns the TensorFlowLite
/// model object or Error in case something went wrong.
Expected<const tflite::Model *> readModel(std::vector<char> &modelData,
const std::string &modelFilename) {
// Open file.
std::ifstream modelFile;
modelFile.open(modelFilename, std::ios::binary);
RETURN_ERR_IF_NOT(modelFile.is_open(),
strFormat("TensorFlowLite: Error opening model file '%s'!",
modelFilename.c_str()));
// Get model size.
modelFile.seekg(0, std::ios::end);
std::streamsize modelSize = modelFile.tellg();
modelFile.seekg(0, std::ios::beg);
// Read model data.
modelData = std::vector<char>(modelSize);
RETURN_ERR_IF_NOT(modelFile.read(modelData.data(), modelSize),
strFormat("TensorFlowLite: Error reading model file '%s'!",
modelFilename.c_str()));
modelFile.close();
// Return model object.
return tflite::GetModel(modelData.data());
}
/// Function to convert the UINT8 data from the buffer \p inpPtr to INT8 format
/// into the buffer \p outPtr. The buffer size is given by \p numElem. This
/// function is used to transform the UINT8 weights of a TensorFlowLite model to
/// INT8 format which is the format preferred and supported by Glow.
void convertUint8ToInt8(const uint8_t *inpPtr, int8_t *outPtr, size_t numElem) {
for (size_t idx = 0, idxEnd = numElem; idx < idxEnd; ++idx) {
int32_t val = inpPtr[idx];
val -= UINT8_TO_INT8_SHIFT;
outPtr[idx] = static_cast<int8_t>(val);
}
}
/// Function to compute the padding according to the TensorFlowLite "SAME"
/// algorithm along a single dimension for the given input size \p inputSize and
/// output size \p outputSize and for the given filter (kernel) size \p kernel
/// \p stride and \p dilation. \returns a pair with the padding to be used for
/// the input before and after the actual input data.
std::pair<unsigned_t, unsigned_t> getSamePads(dim_t inputSize, dim_t outputSize,
unsigned_t kernel,
unsigned_t stride,
unsigned_t dilation = 1) {
// Effective dilated filter (kernel) size.
unsigned_t effKernel = (kernel - 1) * dilation + 1;
// Compute the total padding size while saturating above 0.
unsigned_t padTotal = (outputSize - 1) * stride + effKernel;
padTotal = std::max(padTotal, static_cast<unsigned_t>(inputSize)) - inputSize;
// We split the total padding evenly before/after. If the padding is odd then
// the "after" part gets the extra unit.
unsigned_t padBefore = padTotal / 2;
unsigned_t padAfter = padTotal - padBefore;
return std::pair<unsigned_t, unsigned_t>(padBefore, padAfter);
}
/// Function to verify the quantization parameters of the bias operand. The
/// TensorFlowLite format mandates that the bias scale must be equal to the
/// product inputScale * weightsScale and the bias offset must be 0. This
/// function is provided with the module \p mod and the node values \p input,
/// \p weights, \p bias and \returns Error::success() if the bias parameters
/// are valid and Error otherwise.
Error checkBiasQuantizationParams(Module &mod, NodeValue input,
NodeValue weights, NodeValue bias) {
auto inputTy = input.getType();
auto weightsTy = weights.getType();
auto biasTy = bias.getType();
if (inputTy->isQuantizedType() && weightsTy->isQuantizedType() &&
biasTy->isQuantizedType()) {
float inputScale = inputTy->getScale();
float weightsScale = weightsTy->getScale();
float matMulScale = inputScale * weightsScale;
float biasScale = biasTy->getScale();
// Check bias scale relative error to inputScale * weightsScale.
if (biasScale != matMulScale) {
float relErr = std::abs(matMulScale - biasScale) / matMulScale;
llvm::errs() << strFormat(
"TensorFlowLite: WARNING: Bias scale value was expected "
"to be exactly %E (inputScale * weightsScale) but found "
"%E instead! Relative absolute error is %E!\n",
matMulScale, biasScale, relErr);
if (relErr < tfliteBiasScaleCheckMaxErrorOpt) {
// Set new bias type.
TypeRef newBiasTy =
mod.uniqueType(biasTy->getElementType(), biasTy->dims(),
matMulScale, biasTy->getOffset());
bias.setType(newBiasTy);
// If bias is constant we must also change the payload type.
if (auto *biasC = llvm::dyn_cast<Constant>(bias.getNode())) {
biasC->setPayloadType(newBiasTy);
}
} else if (tfliteBiasScaleCheckThrowErrorOpt) {
RETURN_ERR(
strFormat("TensorFlowLite: ERROR: Bias scale value was expected "
"to be exactly %E (inputScale * weightsScale) but found "
"%E instead! Relative absolute error is %E!\n",
matMulScale, biasScale, relErr));
}
}
int32_t biasOffset = biasTy->getOffset();
if (biasOffset != 0) {
RETURN_ERR(strFormat("TensorFlowLite: Bias offset value was expected to "
"be 0 but found %d instead!",
biasOffset));
}
}
return Error::success();
}
} // namespace
///===---------------------------------------------------------------------===//
/// Tensor Utilities
///===---------------------------------------------------------------------===//
Expected<const tflite::Tensor *>
TFLiteModelLoader::getTensorByIndex(size_t index) {
auto *tensors = graph_->tensors();
RETURN_ERR_IF_NOT(
index < tensors->size(),
strFormat("TensorFlowLite: Tensor index %zu out of range!", index));
return (*tensors)[index];
}
std::string TFLiteModelLoader::getTensorName(const tflite::Tensor *tensor) {
return tensor->name()->str();
}
Expected<std::vector<dim_t>>
TFLiteModelLoader::getTensorShape(const tflite::Tensor *tensor) {
std::vector<dim_t> shape;
for (auto dim : *(tensor->shape())) {
RETURN_ERR_IF_NOT(dim > 0,
strFormat("TensorFlowLite: Tensor '%s' has invalid shape "
"element '%d'!",
getTensorName(tensor).c_str(), dim));
shape.push_back(static_cast<dim_t>(dim));
}
// If tensor shape is empty (scalar) we use a 1D shape with size 1.
if (shape.empty()) {
shape = {1};
}
return shape;
}
Expected<ElemKind>
TFLiteModelLoader::getTensorElemKind(const tflite::Tensor *tensor) {
bool isQuantized = isTensorQuantized(tensor);
switch (tensor->type()) {
case tflite::TensorType_FLOAT32: {
RETURN_ERR_IF_NOT(
!isQuantized,
"TensorFlowLite: FLOAT32 type should have no quantization parameters!");
return ElemKind::FloatTy;
}
case tflite::TensorType_FLOAT16: {
RETURN_ERR_IF_NOT(
!isQuantized,
"TensorFlowLite: FLOAT16 type should have no quantization parameters!");
return ElemKind::Float16Ty;
}
case tflite::TensorType_INT8: {
if (isQuantized) {
return ElemKind::Int8QTy;
} else {
RETURN_ERR("TensorFlowLite: Non-quantized INT8 type not supported!");
}
}
case tflite::TensorType_UINT8: {
if (isQuantized) {
// Convert UINT8 element type to INT8 element type.
if (tfliteUint8ToInt8Opt) {
return ElemKind::Int8QTy;
} else {
return ElemKind::UInt8QTy;
}
} else {
RETURN_ERR("TensorFlowLite: Non-quantized UINT8 type not supported!");
}
}
case tflite::TensorType_INT16: {
if (isQuantized) {
return ElemKind::Int16QTy;
} else {
RETURN_ERR("TensorFlowLite: Non-quantized INT16 type not supported!");
}
}
case tflite::TensorType_INT32: {
if (isQuantized) {
return ElemKind::Int32QTy;
} else {
return ElemKind::Int32ITy;
}
}
case tflite::TensorType_INT64: {
if (isQuantized) {
RETURN_ERR("TensorFlowLite: Quantized INT64 type not supported!");
} else {
return ElemKind::Int64ITy;
}
}
case tflite::TensorType_BOOL: {
RETURN_ERR_IF_NOT(
!isQuantized,
"TensorFlowLite: BOOL type should have no quantization parameters!");
return ElemKind::BoolTy;
}
default:
RETURN_ERR(strFormat("TensorFlowLite: Tensor '%s' type '%s' not supported!",
getTensorName(tensor).c_str(),
tflite::EnumNameTensorType(tensor->type())));
}
}
bool TFLiteModelLoader::isTensorQuantized(const tflite::Tensor *tensor) {
auto *tensorQParams = tensor->quantization();
if (!tensorQParams) {
return false;
}
auto *scales = tensorQParams->scale();
auto *offsets = tensorQParams->zero_point();
if (!(scales && offsets)) {
return false;
}
if (!(scales->size() && offsets->size())) {
return false;
}
return true;
}
bool TFLiteModelLoader::isTensorPerAxisQuantized(const tflite::Tensor *tensor) {
if (!isTensorQuantized(tensor)) {
return false;
}
auto *tensorQParams = tensor->quantization();
auto *scales = tensorQParams->scale();
auto *offsets = tensorQParams->zero_point();
return (scales->size() > 1) && (offsets->size() > 1);
}
Expected<float>
TFLiteModelLoader::getTensorScale(const tflite::Tensor *tensor) {
auto *tensorQParams = tensor->quantization();
RETURN_ERR_IF_NOT(
isTensorQuantized(tensor),
strFormat("TensorFlowLite: Tensor '%s' has no quantization parameters!",
getTensorName(tensor).c_str()));
RETURN_ERR_IF_NOT(
tensorQParams->details_type() == tflite::QuantizationDetails_NONE,
strFormat("TensorFlowLite: Tensor '%s' has custom quantization which is "
"not supported!",
getTensorName(tensor).c_str()));
auto *scales = tensorQParams->scale();
RETURN_ERR_IF_NOT(scales->size() == 1,
strFormat("TensorFlowLite: Tensor '%s' has %d quantization "
"parameters but only one was expected!",
getTensorName(tensor).c_str(), scales->size()));
float scale = (*scales)[0];
return scale;
}
Expected<int32_t>
TFLiteModelLoader::getTensorOffset(const tflite::Tensor *tensor) {
auto *tensorQParams = tensor->quantization();
RETURN_ERR_IF_NOT(
isTensorQuantized(tensor),
strFormat("TensorFlowLite: Tensor '%s' has no quantization parameters!",
getTensorName(tensor).c_str()));
RETURN_ERR_IF_NOT(
tensorQParams->details_type() == tflite::QuantizationDetails_NONE,
strFormat("TensorFlowLite: Tensor '%s' has custom quantization which is "
"not supported!",
getTensorName(tensor).c_str()));
auto *offsets = tensorQParams->zero_point();
RETURN_ERR_IF_NOT(offsets->size() == 1,
strFormat("TensorFlowLite: Tensor '%s' has %d quantization "
"parameters but only one was expected!",
getTensorName(tensor).c_str(), offsets->size()));
// TensorFlowLite defines the offset as int64 since it also supports int64
// quantized type. Since Glow defines the offset as int32 we perform a cast
// here and also validate that the offset is within the int32 range.
int64_t offsetInt64 = (*offsets)[0];
RETURN_ERR_IF_NOT(
(std::numeric_limits<int32_t>::min() <= offsetInt64) &&
(offsetInt64 <= std::numeric_limits<int32_t>::max()),
strFormat(
"TensorFlowLite: Tensor '%s' has an offset out of the int32 range!",
getTensorName(tensor).c_str()));
int32_t offset = static_cast<int32_t>(offsetInt64);
// Convert UINT8 offset to INT8 offset.
if (tfliteUint8ToInt8Opt && (tensor->type() == tflite::TensorType_UINT8)) {
offset -= UINT8_TO_INT8_SHIFT;
}
return offset;
}
Expected<std::vector<float>>
TFLiteModelLoader::getTensorScales(const tflite::Tensor *tensor) {
auto *tensorQParams = tensor->quantization();
RETURN_ERR_IF_NOT(
isTensorQuantized(tensor),
strFormat("TensorFlowLite: Tensor '%s' has no quantization parameters!",
getTensorName(tensor).c_str()));
RETURN_ERR_IF_NOT(
tensorQParams->details_type() == tflite::QuantizationDetails_NONE,
strFormat("TensorFlowLite: Tensor '%s' has custom quantization which is "
"not supported!",
getTensorName(tensor).c_str()));
auto *scales = tensorQParams->scale();
RETURN_ERR_IF_NOT(scales->size() > 1,
strFormat("TensorFlowLite: Tensor '%s' has %d quantization "
"parameters but at least one was expected!",
getTensorName(tensor).c_str(), scales->size()));
std::vector<float> scalesVec =
std::vector<float>(scales->begin(), scales->end());
return scalesVec;
}
Expected<std::vector<int32_t>>
TFLiteModelLoader::getTensorOffsets(const tflite::Tensor *tensor) {
auto *tensorQParams = tensor->quantization();
RETURN_ERR_IF_NOT(
isTensorQuantized(tensor),
strFormat("TensorFlowLite: Tensor '%s' has no quantization parameters!",
getTensorName(tensor).c_str()));
RETURN_ERR_IF_NOT(
tensorQParams->details_type() == tflite::QuantizationDetails_NONE,
strFormat("TensorFlowLite: Tensor '%s' has custom quantization which is "
"not supported!",
getTensorName(tensor).c_str()));
auto *offsets = tensorQParams->zero_point();
RETURN_ERR_IF_NOT(offsets->size() > 1,
strFormat("TensorFlowLite: Tensor '%s' has %d quantization "
"parameters but at least one was expected!",
getTensorName(tensor).c_str(), offsets->size()));
// TensorFlowLite defines the offset as int64 since it also supports int64
// quantized type. Since Glow defines the offset as int32 we perform a cast
// here and also validate that the offset is within the int32 range.
std::vector<int32_t> offsetsVec;
for (auto offsetInt64 : *offsets) {
RETURN_ERR_IF_NOT(
(std::numeric_limits<int32_t>::min() <= offsetInt64) &&
(offsetInt64 <= std::numeric_limits<int32_t>::max()),
strFormat(
"TensorFlowLite: Tensor '%s' has an offset out of the int32 range!",
getTensorName(tensor).c_str()));
int32_t offset = static_cast<int32_t>(offsetInt64);
// Convert UINT8 offset to INT8 offset.
if (tfliteUint8ToInt8Opt && (tensor->type() == tflite::TensorType_UINT8)) {
offset -= UINT8_TO_INT8_SHIFT;
}
offsetsVec.push_back(offset);
}
return offsetsVec;
}
Expected<Type> TFLiteModelLoader::getTensorType(const tflite::Tensor *tensor) {
ElemKind elemKind;
ASSIGN_VALUE_OR_RETURN_ERR(elemKind, getTensorElemKind(tensor));
std::vector<dim_t> shape;
ASSIGN_VALUE_OR_RETURN_ERR(shape, getTensorShape(tensor));
if (isQuantizedElemKind(elemKind)) {
// If tensor is quantized per-axis we use a dummy scale 1.0 and offset 0.
float scale = 1.0;
int32_t offset = 0;
if (!isTensorPerAxisQuantized(tensor)) {
ASSIGN_VALUE_OR_RETURN_ERR(scale, getTensorScale(tensor));
ASSIGN_VALUE_OR_RETURN_ERR(offset, getTensorOffset(tensor));
}
return Type(elemKind, shape, scale, offset);
} else {
return Type(elemKind, shape);
}
}
Expected<std::pair<const char *, size_t>>
TFLiteModelLoader::getTensorDataAndSize(const tflite::Tensor *tensor) {
uint32_t tensorBufferIdx = tensor->buffer();
auto *modelBuffers = model_->buffers();
RETURN_ERR_IF_NOT(tensorBufferIdx < modelBuffers->size(),
strFormat("TensorFlowLite: Tensor '%s' has a buffer index "
"out of range!",
getTensorName(tensor).c_str()));
const char *tensorData = nullptr;
size_t tensorSize = 0;
if (auto *buffer = (*modelBuffers)[tensorBufferIdx]) {
if (auto *array = buffer->data()) {
if (array->size()) {
tensorData =
const_cast<char *>(reinterpret_cast<const char *>(array->data()));
tensorSize = array->size();
}
}
}
return std::pair<const char *, size_t>(tensorData, tensorSize);
}
///===---------------------------------------------------------------------===//
/// Operator Utilities
///===---------------------------------------------------------------------===//
Expected<tflite::BuiltinOperator>
TFLiteModelLoader::getOperatorCode(const tflite::Operator *op) {
const auto *modelOpCodes = model_->operator_codes();
auto opCodeIdx = op->opcode_index();
RETURN_ERR_IF_NOT(opCodeIdx < modelOpCodes->size(),
strFormat("TensorFlowLite: Missing registration for "
"opcode_index %d!",
opCodeIdx));
auto *opCode = (*modelOpCodes)[opCodeIdx];
auto builtinCode = opCode->builtin_code();
RETURN_ERR_IF_NOT(
(tflite::BuiltinOperator_MIN <= builtinCode) &&
(builtinCode <= tflite::BuiltinOperator_MAX),
strFormat(
"TensorFlowLite: Operator builtin_code %d out of the supported "
"range! You might be using a newer model than currently supported!",
builtinCode));
return builtinCode;
}
Expected<int32_t>
TFLiteModelLoader::getOperatorVersion(const tflite::Operator *op) {
const auto *modelOpCodes = model_->operator_codes();
auto opCodeIdx = op->opcode_index();
RETURN_ERR_IF_NOT(opCodeIdx < modelOpCodes->size(),
strFormat("TensorFlowLite: Missing registration for "
"opcode_index %d!",
opCodeIdx));
auto *opCode = (*modelOpCodes)[opCodeIdx];
return opCode->version();
}
Expected<std::string>
TFLiteModelLoader::getOperatorType(const tflite::Operator *op) {
tflite::BuiltinOperator opCode;
ASSIGN_VALUE_OR_RETURN_ERR(opCode, getOperatorCode(op));
return std::string(tflite::EnumNameBuiltinOperator(opCode));
}
Expected<std::string>
TFLiteModelLoader::getOperatorName(const tflite::Operator *op) {
std::string opType;
ASSIGN_VALUE_OR_RETURN_ERR(opType, getOperatorType(op));
const auto *opOutputs = op->outputs();
// If operator has no outputs then we return the operator type name.
if (opOutputs->size() == 0) {
return opType;
}
// If the first output tensor corresponds to an output placeholder then we use
// the operator type name in order to preserve the output placeholder name.
size_t opOutIdx = static_cast<size_t>((*opOutputs)[0]);
const auto *graphOutputs = graph_->outputs();
for (auto graphOutIdx : (*graphOutputs)) {
if (opOutIdx == graphOutIdx) {
return opType;
}
}
// Return the name of the first output tensor.
const tflite::Tensor *tensor;
ASSIGN_VALUE_OR_RETURN_ERR(tensor, getTensorByIndex(opOutIdx));
return getTensorName(tensor);
}
Expected<size_t>
TFLiteModelLoader::getOperatorInputTensorIdx(const tflite::Operator *op,
size_t inputIdx) {
std::string opType;
ASSIGN_VALUE_OR_RETURN_ERR(opType, getOperatorType(op));
const auto *opInputs = op->inputs();
RETURN_ERR_IF_NOT(opInputs,
strFormat("TensorFlowLite: Operator '%s' has no inputs!",
opType.c_str()));
RETURN_ERR_IF_NOT(inputIdx < opInputs->size(),
strFormat("TensorFlowLite: Operator '%s' input index %zu "
"is out of range! Operator has %d inputs!",
opType.c_str(), inputIdx, opInputs->size()));
return static_cast<size_t>((*opInputs)[inputIdx]);
}
Expected<size_t>
TFLiteModelLoader::getOperatorOutputTensorIdx(const tflite::Operator *op,
size_t outputIdx) {
std::string opType;
ASSIGN_VALUE_OR_RETURN_ERR(opType, getOperatorType(op));
const auto *opOutputs = op->outputs();
RETURN_ERR_IF_NOT(opOutputs,
strFormat("TensorFlowLite: Operator '%s' has no outputs!",
opType.c_str()));
RETURN_ERR_IF_NOT(outputIdx < opOutputs->size(),
strFormat("TensorFlowLite: Operator '%s' output index %zu "
"is out of range! Operator has %d outputs!",
opType.c_str(), outputIdx, opOutputs->size()));
return static_cast<size_t>((*opOutputs)[outputIdx]);
}
Expected<bool>
TFLiteModelLoader::isOperatorOutputFinalTensor(const tflite::Operator *op,
size_t outputIdx) {
size_t tensorIdx;
ASSIGN_VALUE_OR_RETURN_ERR(tensorIdx,
getOperatorOutputTensorIdx(op, outputIdx));
const auto *graphOutputs = graph_->outputs();
for (auto graphOutIdx : (*graphOutputs)) {
if (tensorIdx == graphOutIdx) {
return true;
}
}
return false;
}
Expected<NodeValue> TFLiteModelLoader::getNodeValueByIndex(size_t index) {
RETURN_ERR_IF_NOT(!nodeValueByIndex_.empty(),
"TensorFlowLite: Node value array not initialized!");
RETURN_ERR_IF_NOT(
index < nodeValueByIndex_.size(),
strFormat("TensorFlowLite: Node value index %zu is out of range!",
index));
NodeValue nodeValue = nodeValueByIndex_[index];
RETURN_ERR_IF_NOT(nodeValue.getNode(),
strFormat("TensorFlowLite: Node value with index %zu is "
"null (not initialized)!",
index));
return nodeValue;
}
Error TFLiteModelLoader::setNodeValueByIndex(size_t index,
NodeValue nodeValue) {
RETURN_ERR_IF_NOT(!nodeValueByIndex_.empty(),
"TensorFlowLite: Node value array not initialized!");
RETURN_ERR_IF_NOT(
index < nodeValueByIndex_.size(),
strFormat("TensorFlowLite: Node value index %zu is out of range!",
index));
nodeValueByIndex_[index] = nodeValue;
return Error::success();
}
Expected<NodeValue>
TFLiteModelLoader::getInputNodeValue(const tflite::Operator *op,
size_t inputIdx) {
size_t tensorIdx;
ASSIGN_VALUE_OR_RETURN_ERR(tensorIdx,
getOperatorInputTensorIdx(op, inputIdx));
return getNodeValueByIndex(tensorIdx);
}
Error TFLiteModelLoader::setOutputNodeValue(const tflite::Operator *op,
NodeValue nodeValue) {
std::vector<NodeValue> nodeValues = {nodeValue};
return setOutputNodeValues(op, nodeValues);
}
Error TFLiteModelLoader::setOutputNodeValues(
const tflite::Operator *op, llvm::ArrayRef<NodeValue> nodeValues) {
std::string opType;
ASSIGN_VALUE_OR_RETURN_ERR(opType, getOperatorType(op));
const auto *opOutputs = op->outputs();
RETURN_ERR_IF_NOT(
opOutputs->size() == nodeValues.size(),
strFormat("TensorFlowLite: Operator '%s' has %d outputs but %zu are set!",
opType.c_str(), opOutputs->size(), nodeValues.size()));
for (size_t idx = 0, idxEnd = nodeValues.size(); idx < idxEnd; ++idx) {
NodeValue outNodeValue = nodeValues[idx];
// Verify the output type of the node value matches the type registered in
// the model with the exception of the final tensors which are allowed to
// be modified (for example for the Softmax output when it is a final node).
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, idx));
bool isFinal;
ASSIGN_VALUE_OR_RETURN_ERR(isFinal, isOperatorOutputFinalTensor(op, idx));
RETURN_ERR_IF_NOT(isFinal || outTy->isEqual(outNodeValue.getType()),
strFormat("TensorFlowLite: Operator '%s' modifies the "
"output type registered in the model!",
opType.c_str()));
// Register the output node value.
size_t tensorIdx = static_cast<size_t>((*opOutputs)[idx]);
RETURN_IF_ERR(setNodeValueByIndex(tensorIdx, outNodeValue));
}
return Error::success();
}
Expected<TypeRef> TFLiteModelLoader::getOutputType(const tflite::Operator *op,
size_t outputIndex) {
size_t tensorIdx;
ASSIGN_VALUE_OR_RETURN_ERR(tensorIdx,
getOperatorOutputTensorIdx(op, outputIndex));
const tflite::Tensor *tensor;
ASSIGN_VALUE_OR_RETURN_ERR(tensor, getTensorByIndex(tensorIdx));
Type type;
ASSIGN_VALUE_OR_RETURN_ERR(type, getTensorType(tensor));
return mod_.uniqueType(type);
}
void TFLiteModelLoader::initializeNodeValues() {
auto numTensors = graph_->tensors()->size();
nodeValueByIndex_ = std::vector<NodeValue>(numTensors, nullptr);
}
Error TFLiteModelLoader::loadInputPlaceholders() {
for (auto inpIdx : *(graph_->inputs())) {
// Get input placeholder name and type.
const tflite::Tensor *tensor;
ASSIGN_VALUE_OR_RETURN_ERR(tensor, getTensorByIndex(inpIdx));
std::string name = getTensorName(tensor);
Type type;
ASSIGN_VALUE_OR_RETURN_ERR(type, getTensorType(tensor));
// Create input placeholder. If the input type is quantized and a float
// input is requested then we create a float placeholder and a Quantize
// node, otherwise we create directly the quantized placeholder.
Placeholder *inpPH;
NodeValue inpNV;
if (tfliteFloatInputsOpt && type.isQuantizedType()) {
TypeRef floatType = mod_.uniqueType(ElemKind::FloatTy, type.dims());
inpPH = mod_.createPlaceholder(floatType, name, /*isTrainable*/ false,
ANY_LAYOUT);
inpNV = F_->createQuantize(name + ".Quantize", inpPH, &type);
} else {
inpPH = mod_.createPlaceholder(&type, name, /*isTrainable*/ false,
ANY_LAYOUT);
inpNV = inpPH;
}
// Register placeholder by model input name.
inputPlaceholderByName_.try_emplace(name, inpPH);
// Set input node value.
RETURN_IF_ERR(setNodeValueByIndex(inpIdx, inpNV));
}
return Error::success();
}
Error TFLiteModelLoader::loadConstants() {
const auto *tensors = graph_->tensors();
for (size_t idx = 0, idxEnd = tensors->size(); idx < idxEnd; ++idx) {
// Get tensor data and size. A TensorFlowLite model tensor is a constant
// if it has data stored in the model.
const tflite::Tensor *tensor = (*tensors)[idx];
std::pair<const char *, size_t> dataAndSize;
ASSIGN_VALUE_OR_RETURN_ERR(dataAndSize, getTensorDataAndSize(tensor));
if (dataAndSize.first == nullptr) {
continue;
}
// Create tensor and initialize data.
std::string name = getTensorName(tensor);
Type type;
ASSIGN_VALUE_OR_RETURN_ERR(type, getTensorType(tensor));
RETURN_ERR_IF_NOT(
type.getSizeInBytes() == dataAndSize.second,
strFormat("TensorFlowLite: Tensor '%s' mismatch between shape based "
"size (%zu bytes) and actual data size (%lu bytes)!",
name.c_str(), type.getSizeInBytes(), dataAndSize.second));
Tensor T = Tensor(type);
T.copyRawFrom(dataAndSize.first);
// Convert UINT8 data to INT8 data.
if (tfliteUint8ToInt8Opt && (tensor->type() == tflite::TensorType_UINT8)) {
convertUint8ToInt8(reinterpret_cast<uint8_t *>(T.getUnsafePtr()),
reinterpret_cast<int8_t *>(T.getUnsafePtr()),
dataAndSize.second);
}
// Create constant.
Constant *node = mod_.createConstant(name, std::move(T), ANY_LAYOUT);
// Register node value.
RETURN_IF_ERR(setNodeValueByIndex(idx, node->getOutput()));
}
return Error::success();
}
Error TFLiteModelLoader::loadOperators() {
OperatorInfo opInfo;
auto *graphOperators = graph_->operators();
for (size_t opIdx = 0, opIdxEnd = graphOperators->size(); opIdx < opIdxEnd;
++opIdx) {
// Get operator meta data.
const tflite::Operator *op = (*graphOperators)[opIdx];
ASSIGN_VALUE_OR_RETURN_ERR(opInfo.name, getOperatorName(op));
ASSIGN_VALUE_OR_RETURN_ERR(opInfo.type, getOperatorType(op));
ASSIGN_VALUE_OR_RETURN_ERR(opInfo.code, getOperatorCode(op));
ASSIGN_VALUE_OR_RETURN_ERR(opInfo.version, getOperatorVersion(op));
opInfo.index = opIdx;
// Load operator.
mod_.registerOriginalName(opInfo.name);
RETURN_IF_ERR(loadOperator(op, opInfo));
}
return Error::success();
}
Error TFLiteModelLoader::saveOutputPlaceholders() {
for (auto outIdx : *(graph_->outputs())) {
// Get placeholder name.
const tflite::Tensor *tensor;
ASSIGN_VALUE_OR_RETURN_ERR(tensor, getTensorByIndex(outIdx));
std::string name = getTensorName(tensor);
// Save output placeholder. If the output type is quantized and a float
// output is requested then we create create a Dequantize node and save
// into a float placeholder, otherwise we save the quantized placeholder.
NodeValue outNodeValue;
ASSIGN_VALUE_OR_RETURN_ERR(outNodeValue, getNodeValueByIndex(outIdx));
if (tfliteFloatOutputsOpt && outNodeValue.getType()->isQuantizedType()) {
outNodeValue = F_->createDequantize(name + ".Dequantize", outNodeValue,
ElemKind::FloatTy);
}
auto *saveNode = F_->createSave(name, outNodeValue);
// Register placeholder by model output name.
outputPlaceholderByName_.try_emplace(name, saveNode->getPlaceholder());
}
return Error::success();
}
Error TFLiteModelLoader::addActivation(NodeValue &value,
tflite::ActivationFunctionType type) {
std::string nodeName = value.getNode()->getName().str();
std::string actType = EnumNameActivationFunctionType(type);
std::string actName = nodeName + "." + actType;
if (type == tflite::ActivationFunctionType_NONE) {
return Error::success();
}
if (type == tflite::ActivationFunctionType_RELU) {
value = F_->createRELU(actName, value);
return Error::success();
}
if (type == tflite::ActivationFunctionType_RELU_N1_TO_1) {
value = F_->createClip(actName, value, -1.0, 1.0);
return Error::success();
}
if (type == tflite::ActivationFunctionType_RELU6) {
value = F_->createClip(actName, value, 0.0, 6.0);
return Error::success();
}
if (type == tflite::ActivationFunctionType_TANH) {
value = F_->createTanh(actName, value);
return Error::success();
}
RETURN_ERR(strFormat("TensorFlowLite: Activation type '%s' is not supported!",
actType.c_str()));
}
const std::string TFLiteModelLoader::opErrMsg(const OperatorInfo &opInfo,
const std::string &errMsg) {
return strFormat("TensorFlowLite: Operator '%s' (Index %zu, Code %u): %s",
opInfo.type.c_str(), opInfo.index, opInfo.code,
errMsg.c_str());
}
template <typename T>
Expected<T> TFLiteModelLoader::loadAxis(const OperatorInfo &opInfo,
NodeValue axis, NodeValue value) {
Constant *axisC = llvm::dyn_cast<Constant>(axis.getNode());
RETURN_ERR_IF_NOT(axisC,
opErrMsg(opInfo, "Non constant axis not supported!"));
RETURN_ERR_IF_NOT(axisC->getType()->size() == 1,
opErrMsg(opInfo, "Axis should have 1 element!"));
T axisVal;
auto elemType = axisC->getType()->getElementType();
if (elemType == ElemKind::Int32ITy) {
auto axisH = axisC->getPayload().getHandle<int32_t>();
ASSIGN_VALUE_OR_RETURN_ERR(
axisVal, getPositiveAxis<T>(static_cast<int>(axisH.raw(0)), value));
} else if (elemType == ElemKind::Int64ITy) {
auto axisH = axisC->getPayload().getHandle<int64_t>();
ASSIGN_VALUE_OR_RETURN_ERR(
axisVal, getPositiveAxis<T>(static_cast<int>(axisH.raw(0)), value));
} else {
RETURN_ERR(opErrMsg(opInfo, "Axis should have INT32 or INT64 type!"));
}
return axisVal;
}
template <typename T>
Expected<std::vector<T>> TFLiteModelLoader::loadAxes(const OperatorInfo &opInfo,
NodeValue axes,
NodeValue value) {
Constant *axesC = llvm::dyn_cast<Constant>(axes.getNode());
RETURN_ERR_IF_NOT(axesC,
opErrMsg(opInfo, "Non constant axis not supported!"));
RETURN_ERR_IF_NOT(axesC->getType()->size() >= 1,
opErrMsg(opInfo, "Axis should have at least 1 element!"));
std::vector<T> axesVal = std::vector<T>(axesC->getType()->size());
auto elemType = axesC->getType()->getElementType();
for (size_t idx = 0; idx < axesC->getType()->size(); ++idx) {
if (elemType == ElemKind::Int32ITy) {
auto axesH = axesC->getPayload().getHandle<int32_t>();
ASSIGN_VALUE_OR_RETURN_ERR(
axesVal[idx],
getPositiveAxis<T>(static_cast<int>(axesH.raw(idx)), value));
} else if (elemType == ElemKind::Int64ITy) {
auto axesH = axesC->getPayload().getHandle<int64_t>();
ASSIGN_VALUE_OR_RETURN_ERR(
axesVal[idx],
getPositiveAxis<T>(static_cast<int>(axesH.raw(idx)), value));
} else {
RETURN_ERR(opErrMsg(opInfo, "Axis should have INT32 or INT64 type!"));
}
}
return axesVal;
}
template <typename T>
Expected<std::vector<T>>
TFLiteModelLoader::loadArray(const OperatorInfo &opInfo, NodeValue value) {
Constant *valueC = llvm::dyn_cast<Constant>(value.getNode());
RETURN_ERR_IF_NOT(valueC,
opErrMsg(opInfo, "Non constant array not supported!"));
auto valueSize = valueC->getType()->size();
RETURN_ERR_IF_NOT(valueSize >= 1,
opErrMsg(opInfo, "Array should have at least 1 element!"));
std::vector<T> valueV = std::vector<T>(valueSize);
auto elemType = valueC->getType()->getElementType();
for (size_t idx = 0; idx < valueSize; ++idx) {
if (elemType == ElemKind::FloatTy) {
auto valueH = valueC->getPayload().getHandle<float>();
valueV[idx] = static_cast<T>(valueH.raw(idx));
} else if (elemType == ElemKind::Int32ITy) {
auto valueH = valueC->getPayload().getHandle<int32_t>();
valueV[idx] = static_cast<T>(valueH.raw(idx));
} else if (elemType == ElemKind::Int64ITy) {
auto valueH = valueC->getPayload().getHandle<int64_t>();
valueV[idx] = static_cast<T>(valueH.raw(idx));
} else {
RETURN_ERR(opErrMsg(opInfo, "Array type not supported!"));
}
}
return valueV;
}
Expected<bool> TFLiteModelLoader::isConv2DPerAxisQuantized(
const tflite::Operator *op, const OperatorInfo &opInfo,
Constant *&filterScalesC, Constant *&filterOffsetsC, Constant *&biasScalesC,
Constant *&biasOffsetsC) {
// Get filter/bias tensors.
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
size_t filterTensorIdx;
ASSIGN_VALUE_OR_RETURN_ERR(filterTensorIdx, getOperatorInputTensorIdx(op, 1));
size_t biasTensorIdx;
ASSIGN_VALUE_OR_RETURN_ERR(biasTensorIdx, getOperatorInputTensorIdx(op, 2));
const tflite::Tensor *filterTensor;
ASSIGN_VALUE_OR_RETURN_ERR(filterTensor, getTensorByIndex(filterTensorIdx));
const tflite::Tensor *biasTensor;
ASSIGN_VALUE_OR_RETURN_ERR(biasTensor, getTensorByIndex(biasTensorIdx));
bool isPerAxisQuantized = isTensorPerAxisQuantized(filterTensor) &&
isTensorPerAxisQuantized(biasTensor);
// If it is not per-axis quantized return directly.
if (!isPerAxisQuantized) {
filterScalesC = nullptr;
filterOffsetsC = nullptr;
biasScalesC = nullptr;
biasOffsetsC = nullptr;
return false;
}
dim_t numChannels = outTy->dims().back();
// Get filter/bias quantization parameters.
std::vector<float> filterScalesV;
ASSIGN_VALUE_OR_RETURN_ERR(filterScalesV, getTensorScales(filterTensor));
std::vector<int32_t> filterOffsetsV;
ASSIGN_VALUE_OR_RETURN_ERR(filterOffsetsV, getTensorOffsets(filterTensor));
std::vector<float> biasScalesV;
ASSIGN_VALUE_OR_RETURN_ERR(biasScalesV, getTensorScales(biasTensor));
std::vector<int32_t> biasOffsetsV;
ASSIGN_VALUE_OR_RETURN_ERR(biasOffsetsV, getTensorOffsets(biasTensor));
// Create filter/bias quantization parameters graph constants.
filterScalesC =
mod_.createConstant(ElemKind::FloatTy, {numChannels}, "filterScales");
filterOffsetsC =
mod_.createConstant(ElemKind::Int32ITy, {numChannels}, "filterOffsets");
biasScalesC =
mod_.createConstant(ElemKind::FloatTy, {numChannels}, "biasScales");
biasOffsetsC =
mod_.createConstant(ElemKind::Int32ITy, {numChannels}, "biasOffsets");
RETURN_ERR_IF_NOT(
filterScalesV.size() == numChannels,
opErrMsg(opInfo,
"Weights scales length should match the output channels!"));
RETURN_ERR_IF_NOT(
filterOffsetsV.size() == numChannels,
opErrMsg(opInfo,
"Weights offsets length should match the output channels!"));
RETURN_ERR_IF_NOT(
biasScalesV.size() == numChannels,
opErrMsg(opInfo, "Bias scales length should match the output channels!"));
RETURN_ERR_IF_NOT(
biasOffsetsV.size() == numChannels,
opErrMsg(opInfo,
"Bias offsets length should match the output channels!"));
filterScalesC->getPayloadMutable().copyRawFrom(
reinterpret_cast<const char *>(filterScalesV.data()));
filterOffsetsC->getPayloadMutable().copyRawFrom(
reinterpret_cast<const char *>(filterOffsetsV.data()));
biasScalesC->getPayloadMutable().copyRawFrom(
reinterpret_cast<const char *>(biasScalesV.data()));
biasOffsetsC->getPayloadMutable().copyRawFrom(
reinterpret_cast<const char *>(biasOffsetsV.data()));
// Validate filter/bias quantization parameters.
float inputScale = input.getType()->getScale();
auto filterScalesH = filterScalesC->getPayload().getHandle<float>();
auto filterOffsetsH = filterOffsetsC->getPayload().getHandle<int32_t>();
auto biasScalesH = biasScalesC->getPayload().getHandle<float>();
auto biasOffsetsH = biasOffsetsC->getPayload().getHandle<int32_t>();
for (size_t idx = 0; idx < numChannels; ++idx) {
// TensorFlowLite mandates that filterOffset and biasOffset are 0.
RETURN_ERR_IF_NOT(filterOffsetsH.raw(idx) == 0,
opErrMsg(opInfo, "Filter offset was expected to be 0!"));
RETURN_ERR_IF_NOT(biasOffsetsH.raw(idx) == 0,
opErrMsg(opInfo, "Bias offset was expected to be 0!"));
float filterScale = filterScalesH.raw(idx);
float matMulScale = inputScale * filterScale;
float biasScale = biasScalesH.raw(idx);
// Check bias scale relative error to inputScale * filterScale.
if (biasScale != matMulScale) {
float relErr = std::abs(matMulScale - biasScale) / matMulScale;
llvm::errs() << opErrMsg(
opInfo,
strFormat("WARNING: Bias scale value was expected "
"to be exactly %E (inputScale * weightsScale) but found "
"%E instead! Relative absolute error is %E!\n",
matMulScale, biasScale, relErr));
if (relErr < tfliteBiasScaleCheckMaxErrorOpt) {
// Modify bias scale.
biasScalesH.raw(idx) = matMulScale;
} else if (tfliteBiasScaleCheckThrowErrorOpt) {
RETURN_ERR(opErrMsg(
opInfo,
strFormat("ERROR: Bias scale value was expected "
"to be exactly %E (inputScale * weightsScale) but found "
"%E instead! Relative absolute error is %E!\n",
matMulScale, biasScale, relErr)));
}
}
}
return true;
}
Error TFLiteModelLoader::loadOperator(const tflite::Operator *op,
const OperatorInfo &opInfo) {
// Opcodes are treated in increasing order to allow easy tracking
// for which operators are supported and which are not.
auto opCode = opInfo.code;
if (opCode == tflite::BuiltinOperator_ADD) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_AVERAGE_POOL_2D) {
return loadPool2D(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_CONCATENATION) {
return loadConcat(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_CONV_2D) {
return loadConv2D(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_DEPTHWISE_CONV_2D) {
return loadDepthwiseConv2D(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_DEQUANTIZE) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_FLOOR) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_FULLY_CONNECTED) {
return loadFullyConnected(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LOGISTIC) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_MAX_POOL_2D) {
return loadPool2D(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_MUL) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_RELU) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_RELU_N1_TO_1) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_RELU6) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_RESHAPE) {
return loadReshape(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SOFTMAX) {
return loadSoftmax(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_TANH) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_PAD) {
return loadPad(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_TRANSPOSE) {
return loadTranspose(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_MEAN) {
return loadReduce(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SUB) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_DIV) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SQUEEZE) {
return loadReshape(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_EXP) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SPLIT) {
return loadSplit(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_PRELU) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_MAXIMUM) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_ARG_MAX) {
return loadArg(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_MINIMUM) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LESS) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_NEG) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_GREATER) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_GREATER_EQUAL) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LESS_EQUAL) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SLICE) {
return loadSlice(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SIN) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_TILE) {
return loadTile(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_EXPAND_DIMS) {
return loadReshape(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_EQUAL) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_NOT_EQUAL) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LOG) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SQRT) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_RSQRT) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_POW) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_ARG_MIN) {
return loadArg(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_PACK) {
return loadPack(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LOGICAL_OR) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LOGICAL_AND) {
return loadBinaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LOGICAL_NOT) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_UNPACK) {
return loadUnpack(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_SQUARE) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_LEAKY_RELU) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_ABS) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_CEIL) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_COS) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_QUANTIZE) {
return loadUnaryArithmetic(op, opInfo);
}
if (opCode == tflite::BuiltinOperator_ROUND) {
return loadUnaryArithmetic(op, opInfo);
}
RETURN_ERR(strFormat("TensorFlowLite: Operator type '%s' is not supported!",
opInfo.type.c_str()));
}
Error TFLiteModelLoader::loadUnaryArithmetic(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
auto opCode = opInfo.code;
NodeValue output;
if (opCode == tflite::BuiltinOperator_LOGISTIC) {
output = F_->createSigmoid(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_RELU) {
output = F_->createRELU(opInfo.name, input, outTy);
} else if (opCode == tflite::BuiltinOperator_RELU_N1_TO_1) {
output = F_->createClip(opInfo.name, input, outTy, -1.0, 1.0);
} else if (opCode == tflite::BuiltinOperator_RELU6) {
output = F_->createClip(opInfo.name, input, outTy, 0.0, 6.0);
} else if (opCode == tflite::BuiltinOperator_TANH) {
output = F_->createTanh(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_EXP) {
output = F_->createExp(opInfo.name, input);
} else if (opCode == tflite::BuiltinOperator_LOG) {
output = F_->createLog(opInfo.name, input, outTy);
} else if (opCode == tflite::BuiltinOperator_LEAKY_RELU) {
const auto *opts = op->builtin_options_as_LeakyReluOptions();
float alpha = opts->alpha();
output = F_->createLeakyRELU(opInfo.name, outTy, input, alpha);
} else if (opCode == tflite::BuiltinOperator_SQUARE) {
output = F_->createSquare(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_ABS) {
output = F_->createAbs(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_NEG) {
output = F_->createNeg(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_FLOOR) {
output = F_->createFloor(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_CEIL) {
output = F_->createCeil(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_ROUND) {
output = F_->createRound(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_SQRT) {
output = F_->createSqrt(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_RSQRT) {
output = F_->createRsqrt(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_SIN) {
output = F_->createSin(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_COS) {
output = F_->createCos(opInfo.name, outTy, input);
} else if (opCode == tflite::BuiltinOperator_LOGICAL_NOT) {
output = F_->createNot(opInfo.name, input);
} else if (opCode == tflite::BuiltinOperator_QUANTIZE) {
output = F_->createQuantize(opInfo.name, input, outTy);
} else if (opCode == tflite::BuiltinOperator_DEQUANTIZE) {
output = F_->createDequantize(opInfo.name, input, outTy);
} else {
RETURN_ERR(opErrMsg(opInfo, "Unsupported unary arithmetic operator!"));
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadBinaryArithmetic(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue LHS;
ASSIGN_VALUE_OR_RETURN_ERR(LHS, getInputNodeValue(op, 0));
NodeValue RHS;
ASSIGN_VALUE_OR_RETURN_ERR(RHS, getInputNodeValue(op, 1));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
// LHS operand broadcasting.
if (LHS.dims().size() < RHS.dims().size()) {
unsigned_t axis = RHS.dims().size() - LHS.dims().size();
LHS =
F_->createBroadcast(opInfo.name + ".Broadcast", LHS, RHS.dims(), axis);
}
// RHS operand broadcasting.
if (RHS.dims().size() < LHS.dims().size()) {
unsigned_t axis = LHS.dims().size() - RHS.dims().size();
RHS =
F_->createBroadcast(opInfo.name + ".Broadcast", RHS, LHS.dims(), axis);
}
auto opCode = opInfo.code;
NodeValue output;
if (opCode == tflite::BuiltinOperator_ADD) {
const auto *opts = op->builtin_options_as_AddOptions();
output = F_->createAdd(opInfo.name, outTy, LHS, RHS);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
} else if (opCode == tflite::BuiltinOperator_MUL) {
const auto *opts = op->builtin_options_as_MulOptions();
output = F_->createMul(opInfo.name, outTy, LHS, RHS);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
} else if (opCode == tflite::BuiltinOperator_SUB) {
const auto *opts = op->builtin_options_as_SubOptions();
output = F_->createSub(opInfo.name, outTy, LHS, RHS);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
} else if (opCode == tflite::BuiltinOperator_DIV) {
const auto *opts = op->builtin_options_as_DivOptions();
output = F_->createDiv(opInfo.name, outTy, LHS, RHS);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
} else if (opCode == tflite::BuiltinOperator_POW) {
output = F_->createPow(opInfo.name, outTy, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_PRELU) {
NodeValue slope =
F_->createReshape(opInfo.name + ".reshape", RHS, outTy->dims());
output = F_->createPRELU(opInfo.name, LHS, slope, outTy);
} else if (opCode == tflite::BuiltinOperator_MAXIMUM) {
output = F_->createMax(opInfo.name, outTy, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_MINIMUM) {
output = F_->createMin(opInfo.name, outTy, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_EQUAL) {
output = F_->createCmpEQ(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_NOT_EQUAL) {
output = F_->createCmpNEQ(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_LESS) {
output = F_->createCmpLT(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_LESS_EQUAL) {
output = F_->createCmpLTE(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_GREATER) {
output = F_->createCmpGT(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_GREATER_EQUAL) {
output = F_->createCmpGTE(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_LOGICAL_AND) {
output = F_->createAnd(opInfo.name, LHS, RHS);
} else if (opCode == tflite::BuiltinOperator_LOGICAL_OR) {
output = F_->createOr(opInfo.name, LHS, RHS);
} else {
RETURN_ERR(opErrMsg(opInfo, "Unsupported binary arithmetic operator!"));
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadPool2D(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_Pool2DOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
ShapeNHWC inputShape = ShapeNHWC(input.dims());
ShapeNHWC outputShape = ShapeNHWC(outTy->dims());
std::vector<unsigned_t> kernels = {
static_cast<unsigned_t>(opts->filter_height()),
static_cast<unsigned_t>(opts->filter_width())};
std::vector<unsigned_t> strides = {
static_cast<unsigned_t>(opts->stride_h()),
static_cast<unsigned_t>(opts->stride_w()),
};
std::vector<unsigned_t> pads;
if (opts->padding() == tflite::Padding::Padding_VALID) {
pads = {0, 0, 0, 0};
} else if (opts->padding() == tflite::Padding::Padding_SAME) {
auto padsTB =
getSamePads(inputShape.h, outputShape.h, kernels[0], strides[0]);
auto padsLR =
getSamePads(inputShape.w, outputShape.w, kernels[1], strides[1]);
pads = {padsTB.first, padsLR.first, padsTB.second, padsLR.second};
} else {
RETURN_ERR(opErrMsg(opInfo, "Padding parameter invalid!"));
}
auto opCode = opInfo.code;
NodeValue output;
if (opCode == tflite::BuiltinOperator_AVERAGE_POOL_2D) {
auto *node = F_->createAvgPool(opInfo.name, input, kernels, strides, pads);
output = node->getResult();
} else if (opCode == tflite::BuiltinOperator_MAX_POOL_2D) {
auto *node = F_->createMaxPool(opInfo.name, input, kernels, strides, pads);
output = node->getResult();
} else {
RETURN_ERR(opErrMsg(opInfo, "Unsupported Pool2D operator!"));
}
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadConcat(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_ConcatenationOptions();
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
const size_t numInputs = op->inputs()->size();
llvm::SmallVector<NodeValue, 4> inputs;
inputs.reserve(numInputs);
for (size_t idx = 0; idx < numInputs; ++idx) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, idx));
inputs.push_back(input);
}
// If this node is quantized and there is a mismatch between the input and
// output quantization parameters then we pull Rescale nodes from the inputs
// to match the output quantization parameters.
if (outTy->isQuantizedType()) {
for (size_t idx = 0; idx < numInputs; ++idx) {
NodeValue input = inputs[idx];
TypeRef inpTy = input.getType();
RETURN_ERR_IF_NOT(
inpTy->isQuantizedType(),
opErrMsg(opInfo, "Mixed precision for input/output not supported!"));
if ((inpTy->getScale() != outTy->getScale()) ||
(inpTy->getOffset() != outTy->getOffset())) {
TypeRef inpTyNew = mod_.uniqueTypeWithNewShape(outTy, inpTy->dims());
auto *rescaleNode = F_->createRescaleQuantized(
opInfo.name + ".Rescale" + std::to_string(idx), input, inpTyNew);
inputs[idx] = rescaleNode->getResult();
}
}
}
unsigned_t axis;
ASSIGN_VALUE_OR_RETURN_ERR(
axis, getPositiveAxis<unsigned_t>(opts->axis(), outTy->dims().size()));
NodeValue output = F_->createConcat(opInfo.name, inputs, axis, outTy);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadConv2D(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_Conv2DOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue filter;
ASSIGN_VALUE_OR_RETURN_ERR(filter, getInputNodeValue(op, 1));
NodeValue bias;
ASSIGN_VALUE_OR_RETURN_ERR(bias, getInputNodeValue(op, 2));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
ShapeNHWC inputShape = ShapeNHWC(input.dims());
ShapeNHWC filterShape = ShapeNHWC(filter.dims());
ShapeNHWC outputShape = ShapeNHWC(outTy->dims());
std::vector<unsigned_t> kernels = {static_cast<unsigned_t>(filterShape.h),
static_cast<unsigned_t>(filterShape.w)};
std::vector<unsigned_t> strides = {
static_cast<unsigned_t>(opts->stride_h()),
static_cast<unsigned_t>(opts->stride_w()),
};
std::vector<unsigned_t> dilations = {
static_cast<unsigned_t>(opts->dilation_h_factor()),
static_cast<unsigned_t>(opts->dilation_w_factor()),
};
std::vector<unsigned_t> pads;
if (opts->padding() == tflite::Padding::Padding_VALID) {
pads = {0, 0, 0, 0};
} else if (opts->padding() == tflite::Padding::Padding_SAME) {
auto padsTB = getSamePads(inputShape.h, outputShape.h, kernels[0],
strides[0], dilations[0]);
auto padsLR = getSamePads(inputShape.w, outputShape.w, kernels[1],
strides[1], dilations[1]);
pads = {padsTB.first, padsLR.first, padsTB.second, padsLR.second};
} else {
RETURN_ERR(opErrMsg(opInfo, "Padding parameter invalid!"));
}
// TODO: Remove this when Conv2D supports multiple dilations.
RETURN_ERR_IF_NOT(dilations[0] == dilations[1],
opErrMsg(opInfo, "Non square dilation not supported!"));
unsigned_t dilation = dilations[0];
// There are TensorFlowLite models which have only the weights quantized
// to INT8 (the rest of the operands being FLOAT32). Since Glow does not
// support mixed precision operation we dequantize the weights.
if (input.getType()->isFPType() && filter.getType()->isQuantizedType() &&
bias.getType()->isFPType() && outTy->isFPType()) {
filter = F_->createDequantize(opInfo.name + ".Dequantize", filter,
outTy->getElementType());
}
// Check whether this operator is quantized per axis.
bool isPerAxisQuantized;
Constant *filterScales = nullptr;
Constant *filterOffsets = nullptr;
Constant *biasScales = nullptr;
Constant *biasOffsets = nullptr;
ASSIGN_VALUE_OR_RETURN_ERR(isPerAxisQuantized,
isConv2DPerAxisQuantized(op, opInfo, filterScales,
filterOffsets, biasScales,
biasOffsets));
// Create convolution node.
NodeValue output;
if (isPerAxisQuantized) {
// Check that filter and bias are constants.
RETURN_ERR_IF_NOT(llvm::dyn_cast<Constant>(filter.getNode()),
opErrMsg(opInfo, "Filter must be constant!"));
RETURN_ERR_IF_NOT(llvm::dyn_cast<Constant>(bias.getNode()),
opErrMsg(opInfo, "Bias must be constant!"));
// Create ChannelwiseQuantizedConvolution node.
output = F_->createChannelwiseQuantizedConv(
opInfo.name, input, filter, bias, filterScales, filterOffsets,
biasScales, biasOffsets, outTy, kernels, strides, pads, /* group */ 1,
dilation, /* quantizeFilter */ false, /* quantizeBias */ false);
} else {
// Check bias quantization parameters.
RETURN_IF_ERR(checkBiasQuantizationParams(mod_, input, filter, bias));
// Create Convolution node.
output = F_->createConv(opInfo.name, input, filter, bias, outTy, kernels,
strides, pads, /* group */ 1, dilation);
}
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadDepthwiseConv2D(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_DepthwiseConv2DOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue filter;
ASSIGN_VALUE_OR_RETURN_ERR(filter, getInputNodeValue(op, 1));
NodeValue bias;
ASSIGN_VALUE_OR_RETURN_ERR(bias, getInputNodeValue(op, 2));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
ShapeNHWC inputShape = ShapeNHWC(input.dims());
ShapeNHWC filterShape = ShapeNHWC(filter.dims());
ShapeNHWC outputShape = ShapeNHWC(outTy->dims());
std::vector<unsigned_t> kernels = {static_cast<unsigned_t>(filterShape.h),
static_cast<unsigned_t>(filterShape.w)};
std::vector<unsigned_t> strides = {
static_cast<unsigned_t>(opts->stride_h()),
static_cast<unsigned_t>(opts->stride_w()),
};
std::vector<unsigned_t> dilations = {1, 1};
if (opInfo.version >= 2) {
dilations = {static_cast<unsigned_t>(opts->dilation_h_factor()),
static_cast<unsigned_t>(opts->dilation_w_factor())};
}
std::vector<unsigned_t> pads;
if (opts->padding() == tflite::Padding::Padding_VALID) {
pads = {0, 0, 0, 0};
} else if (opts->padding() == tflite::Padding::Padding_SAME) {
auto padsTB = getSamePads(inputShape.h, outputShape.h, kernels[0],
strides[0], dilations[0]);
auto padsLR = getSamePads(inputShape.w, outputShape.w, kernels[1],
strides[1], dilations[1]);
pads = {padsTB.first, padsLR.first, padsTB.second, padsLR.second};
} else {
RETURN_ERR(opErrMsg(opInfo, "Padding parameter invalid!"));
}
// TODO: Remove this when Conv2D supports multiple dilations.
RETURN_ERR_IF_NOT(dilations[0] == dilations[1],
opErrMsg(opInfo, "Non square dilation not supported!"));
unsigned_t dilation = dilations[0];
// Convolution group is inputChannels / filterChannels = inputChannels.
unsigned_t group = input.dims().back();
// There are TensorFlowLite models which have only the weights quantized
// to INT8 (the rest of the operands being FLOAT32). Since Glow does not
// support mixed precision operation we dequantize the weights.
if (input.getType()->isFPType() && filter.getType()->isQuantizedType() &&
bias.getType()->isFPType() && outTy->isFPType()) {
filter = F_->createDequantize(opInfo.name + ".Dequantize", filter,
outTy->getElementType());
}
// Check whether this operator is quantized per axis.
bool isPerAxisQuantized;
Constant *filterScales = nullptr;
Constant *filterOffsets = nullptr;
Constant *biasScales = nullptr;
Constant *biasOffsets = nullptr;
ASSIGN_VALUE_OR_RETURN_ERR(isPerAxisQuantized,
isConv2DPerAxisQuantized(op, opInfo, filterScales,
filterOffsets, biasScales,
biasOffsets));
// Transpose filter from CHWN to NHWC in-place without using a Reshape
// node because further down the ChannelwiseQuantizedConvolution requires
// the filter to be a Constant.
RETURN_ERR_IF_NOT(filter.dims().size() == 4,
opErrMsg(opInfo, "Filter should be 4D!"));
if (isPerAxisQuantized) {
Constant *filterC = llvm::dyn_cast<Constant>(filter.getNode());
RETURN_ERR_IF_NOT(filterC, opErrMsg(opInfo, "Filter must be constant!"));
TypeRef filterTy = filterC->getType();
auto filterDims = filterTy->dims();
TypeRef newFilterTy = mod_.uniqueTypeWithNewShape(
filterTy, {filterDims[3], filterDims[1], filterDims[2], filterDims[0]});
Tensor newFilterT = Tensor(newFilterTy);
filterC->getPayload().transpose(&newFilterT, {3, 1, 2, 0});
Constant *newFilterC = mod_.createConstant(
filterC->getName().str() + ".Reshape", std::move(newFilterT), "NHWC");
filter = newFilterC->getOutput();
} else {
filter = F_->createTranspose(opInfo.name + ".Transpose", filter,
{3, 1, 2, 0}, "NHWC");
}
RETURN_ERR_IF_NOT(filter.dims().back() == 1,
opErrMsg(opInfo, "Filter should have 1 channel!"));
// Create convolution node.
NodeValue output;
if (isPerAxisQuantized) {
// Check that filter and bias are constants.
RETURN_ERR_IF_NOT(llvm::dyn_cast<Constant>(filter.getNode()),
opErrMsg(opInfo, "Filter must be constant!"));
RETURN_ERR_IF_NOT(llvm::dyn_cast<Constant>(bias.getNode()),
opErrMsg(opInfo, "Bias must be constant!"));
// Create ChannelwiseQuantizedConvolution node.
output = F_->createChannelwiseQuantizedConv(
opInfo.name, input, filter, bias, filterScales, filterOffsets,
biasScales, biasOffsets, outTy, kernels, strides, pads, group, dilation,
/* quantizeFilter */ false, /* quantizeBias */ false);
} else {
// Check bias quantization parameters.
RETURN_IF_ERR(checkBiasQuantizationParams(mod_, input, filter, bias));
// Create Convolution node.
output = F_->createConv(opInfo.name, input, filter, bias, outTy, kernels,
strides, pads, group, dilation);
}
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadFullyConnected(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_FullyConnectedOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue weights;
ASSIGN_VALUE_OR_RETURN_ERR(weights, getInputNodeValue(op, 1));
NodeValue bias;
ASSIGN_VALUE_OR_RETURN_ERR(bias, getInputNodeValue(op, 2));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
RETURN_IF_ERR(checkBiasQuantizationParams(mod_, input, weights, bias));
// There are TensorFlowLite models which have only the weights quantized
// to INT8 (the rest of the operands being FLOAT32). Since Glow does not
// support mixed precision operation we dequantize the weights.
if (input.getType()->isFPType() && weights.getType()->isQuantizedType() &&
bias.getType()->isFPType() && outTy->isFPType()) {
weights = F_->createDequantize(opInfo.name + ".Dequantize", weights,
outTy->getElementType());
}
if (opInfo.version >= 2) {
RETURN_ERR_IF_NOT(
opts->weights_format() ==
tflite::FullyConnectedOptionsWeightsFormat_DEFAULT,
opErrMsg(opInfo, "Only default weights format is supported!"));
}
bool keepDims = false;
if (opInfo.version >= 5) {
keepDims = opts->keep_num_dims();
}
// Transpose weights.
RETURN_ERR_IF_NOT(weights.dims().size() == 2,
opErrMsg(opInfo, "Weights should be 2D!"));
weights = F_->createTranspose(opInfo.name + ".Transpose", weights, {1, 0});
// For an input with shape [D(0), D(1), ... , D(N-1)] if:
// keep_num_dims is FALSE then we flatten the input into:
// [D(0), D(1) x D(2) x ... x D(N-1)] (axis = 1).
// keep_num_dims options is TRUE then we flatten the input into:
// [D(0) x D(1) x ... x D(N-2), D(N-1)] (axis = N-1).
unsigned_t axis = keepDims ? (input.dims().size() - 1) : 1;
NodeValue output =
F_->createFullyConnected(opInfo.name, input, weights, bias, outTy, axis);
RETURN_IF_ERR(addActivation(output, opts->fused_activation_function()));
// Expand output dims if necessary.
if (keepDims) {
std::vector<dim_t> outputDims = input.dims();
outputDims.back() = output.dims().back();
output = F_->createReshape(opInfo.name + ".Reshape", output, outputDims);
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadReshape(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
// Note: The Reshape node has a second input operand which provides
// the new shape but the documentation states that is should be ignored
// and the 'new_shape' attribute should be used instead. Moreover, in
// this case we are not using not even the 'new_shape' attribute because
// we have the output type directly available. We are using this logic
// also for loading other operators: Squeeze, ExpandDims.
NodeValue output = F_->createReshape(opInfo.name, input, outTy->dims());
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadSoftmax(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_SoftmaxOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
RETURN_ERR_IF_NOT(input.dims().size() >= 2,
opErrMsg(opInfo, "Input rank must be >= 2!"));
float beta = opts->beta();
// Create a constant to store labels to be used in SoftMaxGradNode.
auto selected =
mod_.createConstant(ElemKind::Int64ITy, {input.dims()[0], 1}, "selected");
NodeValue output;
if (tfliteFloatSoftmaxOpt) {
// We dequantize the input if it is quantized type.
if (input.getType()->isQuantizedType()) {
input = F_->createDequantize(opInfo.name + ".Dequantize", input,
ElemKind::FloatTy);
}
// Create float Softmax regardless of the type defined in the model.
output = F_->createSoftMax(opInfo.name, input, selected, nullptr, beta);
// If target output type is quantized we quantize the float output of the
// Softmax but only if it is not an output placeholder in which case we
// allow the output placeholder to remain float even though it was defined
// as quantized in the original model.
bool isFinal;
ASSIGN_VALUE_OR_RETURN_ERR(isFinal, isOperatorOutputFinalTensor(op, 0));
if (outTy->isQuantizedType() && !isFinal) {
output = F_->createQuantize(opInfo.name + ".Quantize", output, outTy);
}
} else {
output = F_->createSoftMax(opInfo.name, input, selected, outTy, beta);
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadPad(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue pads;
ASSIGN_VALUE_OR_RETURN_ERR(pads, getInputNodeValue(op, 1));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
// Validate paddings shape.
auto numDims = input.dims().size();
RETURN_ERR_IF_NOT(pads.dims().size() == 2,
opErrMsg(opInfo, "Paddings should be 2D!"));
RETURN_ERR_IF_NOT(pads.dims()[0] == numDims,
opErrMsg(opInfo, "Paddings 1st dimension should match the "
"input rank!"));
RETURN_ERR_IF_NOT(pads.dims()[1] == 2,
opErrMsg(opInfo, "Paddings 2nd dimensions should be 2!"));
// TFLite paddings are stored as start(D1),stop(D1),start(D2),stop(D2),etc.
Constant *padsC = llvm::dyn_cast<Constant>(pads.getNode());
RETURN_ERR_IF_NOT(padsC,
opErrMsg(opInfo, "Non constant 'paddings' not supported!"));
RETURN_ERR_IF_NOT(padsC->getType()->getElementType() == ElemKind::Int32ITy,
opErrMsg(opInfo, "Paddings should have INT32 type!"));
auto padsH = padsC->getPayload().getHandle<int32_t>();
std::vector<int> padsVec(padsH.size());
for (dim_t dim = 0; dim < numDims; ++dim) {
auto padStart = padsH.at({dim, 0});
auto padStop = padsH.at({dim, 1});
RETURN_ERR_IF_NOT((padStart >= 0) && (padStop >= 0),
opErrMsg(opInfo, "Invalid negative padding value!"));
padsVec[0 * numDims + dim] = static_cast<int>(padStart);
padsVec[1 * numDims + dim] = static_cast<int>(padStop);
}
NodeValue output = F_->createPad(opInfo.name, input, outTy,
PaddingMode::CONSTANT, padsVec, 0.f);
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadTranspose(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue perm;
ASSIGN_VALUE_OR_RETURN_ERR(perm, getInputNodeValue(op, 1));
Constant *permC = llvm::dyn_cast<Constant>(perm.getNode());
RETURN_ERR_IF_NOT(
permC, opErrMsg(opInfo, "Non constant permutation not supported!"));
RETURN_ERR_IF_NOT(permC->getType()->getElementType() == ElemKind::Int32ITy,
opErrMsg(opInfo, "Permutation should have INT32 type!"));
auto permH = permC->getPayload().getHandle<int32_t>();
std::vector<unsigned_t> shuffle;
for (size_t idx = 0; idx < permH.size(); ++idx) {
int32_t dim = permH.raw(idx);
RETURN_ERR_IF_NOT(dim >= 0, opErrMsg(opInfo, "Invalid permutation value!"));
shuffle.push_back(static_cast<unsigned_t>(dim));
}
NodeValue output = F_->createTranspose(opInfo.name, input, shuffle);
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadReduce(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_ReducerOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue axes;
ASSIGN_VALUE_OR_RETURN_ERR(axes, getInputNodeValue(op, 1));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
std::vector<unsigned_t> axesVal;
ASSIGN_VALUE_OR_RETURN_ERR(axesVal,
loadAxes<unsigned_t>(opInfo, axes, input));
bool keepDims = opts->keep_dims();
// Currently the Glow reduce operators do not support multiple axes so we
// create chained reduce operators with single axis.
// TODO: When Glow supports reduce operators with multiple axes remove this!
auto opCode = opInfo.code;
NodeValue output = input;
for (size_t idx = 0, end = axesVal.size(); idx < end; ++idx) {
// Current axis value.
unsigned_t axisVal = axesVal[idx];
if (!keepDims) {
axisVal = axisVal - idx;
}
// Current output type.
ShapeVector outDimsCurr(output.dims().begin(), output.dims().end());
outDimsCurr.erase(outDimsCurr.begin() + axisVal);
auto outTypeCurr = mod_.uniqueTypeWithNewShape(outTy, outDimsCurr);
// Create reduce operator.
if (opCode == tflite::BuiltinOperator_MEAN) {
output = F_->createBatchedReduceMean(opInfo.name, outTypeCurr, output,
{axisVal});
// The BatchedReduceMean reduces the output dimension and hence we expand
// the output dimensions if keepDims is true.
if (keepDims) {
output =
F_->createExpandDims(opInfo.name + ".Expand", output, {axisVal});
}
} else {
RETURN_ERR(opErrMsg(opInfo, "Unsupported Reduce operator!"));
}
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadSplit(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_SplitOptions();
NodeValue axis;
ASSIGN_VALUE_OR_RETURN_ERR(axis, getInputNodeValue(op, 0));
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 1));
unsigned_t axisVal;
ASSIGN_VALUE_OR_RETURN_ERR(axisVal,
loadAxis<unsigned_t>(opInfo, axis, input));
unsigned_t numSplits = static_cast<unsigned_t>(opts->num_splits());
RETURN_ERR_IF_NOT(
input.dims()[axisVal] % numSplits == 0,
opErrMsg(
opInfo,
"Input dimension should be divisible by 'num_splits' along axis!"));
std::vector<SliceNode *> outputNodes;
F_->createSplit(opInfo.name, input, numSplits, axisVal, {}, outputNodes);
std::vector<NodeValue> outputNodeValues(outputNodes.size(), nullptr);
for (size_t idx = 0, end = outputNodes.size(); idx < end; ++idx) {
outputNodeValues[idx] = outputNodes[idx]->getResult();
}
return setOutputNodeValues(op, outputNodeValues);
}
Error TFLiteModelLoader::loadArg(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue axis;
ASSIGN_VALUE_OR_RETURN_ERR(axis, getInputNodeValue(op, 1));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
unsigned_t axisVal;
ASSIGN_VALUE_OR_RETURN_ERR(axisVal,
loadAxis<unsigned_t>(opInfo, axis, input));
auto opCode = opInfo.code;
NodeValue output = nullptr;
if (opCode == tflite::BuiltinOperator_ARG_MAX) {
output = F_->createArgMax(opInfo.name, input, axisVal, /* keepDims */ false,
outTy->getElementType());
} else if (opCode == tflite::BuiltinOperator_ARG_MIN) {
output = F_->createArgMin(opInfo.name, input, axisVal, /* keepDims */ false,
outTy->getElementType());
} else {
RETURN_ERR(opErrMsg(opInfo, "Unsupported Arg operator!"));
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadSlice(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue begin;
ASSIGN_VALUE_OR_RETURN_ERR(begin, getInputNodeValue(op, 1));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
// Note: Slice has a third input operand 'size' which provides the size of
// the output slice. We derive here the output slice size based on outTy.
Constant *beginC = llvm::dyn_cast<Constant>(begin.getNode());
RETURN_ERR_IF_NOT(beginC,
opErrMsg(opInfo, "Non constant begin not supported!"));
RETURN_ERR_IF_NOT(beginC->getType()->getElementType() == ElemKind::Int32ITy,
opErrMsg(opInfo, "Begin should have INT32 type!"));
auto beginH = beginC->getPayload().getHandle<int32_t>();
std::vector<dim_t> start;
for (size_t idx = 0; idx < beginH.size(); ++idx) {
int32_t dimStart = beginH.raw(idx);
RETURN_ERR_IF_NOT(dimStart >= 0, opErrMsg(opInfo, "Invalid begin value!"));
start.push_back(static_cast<dim_t>(dimStart));
}
NodeValue output = F_->createSlice(opInfo.name, input, start, outTy);
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadTile(const tflite::Operator *op,
const OperatorInfo &opInfo) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
NodeValue multiples;
ASSIGN_VALUE_OR_RETURN_ERR(multiples, getInputNodeValue(op, 1));
auto numDims = input.getType()->dims().size();
std::vector<unsigned_t> numTiles;
ASSIGN_VALUE_OR_RETURN_ERR(numTiles,
loadArray<unsigned_t>(opInfo, multiples));
RETURN_ERR_IF_NOT(numTiles.size() == numDims,
opErrMsg(opInfo, "Input operand 'multiples' length should "
"match the number of input dimensions!"));
NodeValue output = input;
for (unsigned_t axis = 0; axis < numDims; ++axis) {
unsigned_t tiles = numTiles[axis];
if (tiles != 1) {
output = F_->createTile(opInfo.name + std::to_string(axis), output, tiles,
axis);
}
}
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadPack(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_PackOptions();
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
const size_t numInputs = op->inputs()->size();
RETURN_ERR_IF_NOT(numInputs == opts->values_count(),
opErrMsg(opInfo, "Attribute 'values_count' does not match "
"the number of operator inputs!"));
llvm::SmallVector<NodeValue, 4> inputs;
inputs.reserve(numInputs);
for (size_t idx = 0; idx < numInputs; ++idx) {
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, idx));
inputs.push_back(input);
}
unsigned_t axis;
ASSIGN_VALUE_OR_RETURN_ERR(
axis, getPositiveAxis<unsigned_t>(opts->axis(), outTy->dims().size()));
// Validate that all inputs have same shape.
for (size_t idx = 0; idx < numInputs; ++idx) {
RETURN_ERR_IF_NOT(
inputs[idx].getType()->isEqual(inputs[0].getType()),
opErrMsg(opInfo, "Operator inputs do not have same type/shape!"));
}
// Reshape all inputs from [D0,D1,...,DN] to [D0,D1,...,1,...,DN] where the
// the singular dimension 1 is on the axis position.
std::vector<dim_t> inputDimsReshaped = inputs[0].dims();
inputDimsReshaped.insert(inputDimsReshaped.begin() + axis, 1);
for (size_t idx = 0; idx < numInputs; ++idx) {
inputs[idx] =
F_->createReshape(opInfo.name + ".Reshape" + std::to_string(idx),
inputs[idx], inputDimsReshaped);
}
// Concatenate all inputs along axis.
NodeValue output =
F_->createConcat(opInfo.name + ".Concat", inputs, axis, outTy);
return setOutputNodeValue(op, output);
}
Error TFLiteModelLoader::loadUnpack(const tflite::Operator *op,
const OperatorInfo &opInfo) {
const auto *opts = op->builtin_options_as_UnpackOptions();
NodeValue input;
ASSIGN_VALUE_OR_RETURN_ERR(input, getInputNodeValue(op, 0));
TypeRef outTy;
ASSIGN_VALUE_OR_RETURN_ERR(outTy, getOutputType(op, 0));
unsigned_t axis;
ASSIGN_VALUE_OR_RETURN_ERR(axis,
getPositiveAxis<unsigned_t>(opts->axis(), input));
unsigned_t num = static_cast<unsigned_t>(opts->num());
RETURN_ERR_IF_NOT(
num == input.dims()[axis],
opErrMsg(opInfo,
"Attribute 'num' should be equal to input size along axis!"));
// Split input.
std::vector<SliceNode *> outputNodes;
F_->createSplit(opInfo.name, input, num, axis, {}, outputNodes);
// Reshape outputs.
std::vector<NodeValue> outputNodeValues(outputNodes.size(), nullptr);
for (size_t idx = 0, end = outputNodes.size(); idx < end; ++idx) {
outputNodeValues[idx] = outputNodes[idx]->getResult();
outputNodeValues[idx] =
F_->createReshape(opInfo.name + ".Reshape" + std::to_string(idx),
outputNodeValues[idx], outTy->dims());
}
return setOutputNodeValues(op, outputNodeValues);
}
TFLiteModelLoader::TFLiteModelLoader(const std::string &modelFilename,
Function *F)
: F_(F), mod_(*F->getParent()) {
auto setup = [&]() -> Error {
// Read model.
std::vector<char> modelData;
ASSIGN_VALUE_OR_RETURN_ERR(model_, readModel(modelData, modelFilename));
// TODO: Verify model integrity using flatbuffers::Verifier class.
// Get model info.
modelVersion_ = model_->version();
modelDescription_ = model_->description()->str();
// Get model graph.
const auto *modelGraphs = model_->subgraphs();
RETURN_ERR_IF_NOT(
modelGraphs->size() == 1,
"TensorFlowLite: Only one model subgraph is currently supported!");
graph_ = (*modelGraphs)[0];
// Initialize graph node values.
initializeNodeValues();
// Load graph input placeholders.
RETURN_IF_ERR(loadInputPlaceholders());
// Load graph constants.
RETURN_IF_ERR(loadConstants());
// Load graph operators.
RETURN_IF_ERR(loadOperators());
// Save graph output placeholders.
RETURN_IF_ERR(saveOutputPlaceholders());
// Verify function.
RETURN_ERR_IF_NOT(F_->verify(),
"TensorFlowLite: Function verification failed!");
return Error::success();
};
EXIT_ON_ERR(setup());
}
|
[
"[email protected]"
] | |
97cc3b991366b8e97608fb4211e51596ec864851
|
b8443f3202db34d22fcb5ad20cf40b89571f690f
|
/ABC215/ABC215B.cpp
|
8059582296b8bc5dcbd1032f6cc378c04f372343
|
[] |
no_license
|
hika1822/AtcoderBC
|
b1befcfae54fef427cd55d9cd9601f2260817afb
|
aa6be75b905406b1b86a0fddb215dc573ab04136
|
refs/heads/main
| 2023-07-19T09:27:00.933525 | 2021-08-28T15:20:05 | 2021-08-28T15:20:05 | 398,471,176 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 350 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long n;//ๆๆฐใชใฉๅทจๅคงใชๆดๆฐใๆฑใๅ ดๅใฏlong longใไฝฟใ
cin >> n;
long long k = 1;
for(long long i = 0; i <= 99; i++)
{
k = k*2;
if(k > n)
{
cout << i << endl;
break;
}
}
return 0;
}
|
[
"[email protected]"
] | |
08d5611f90d4f1c1ca130834fdeb24978ab8e8df
|
33cc75a925b12133bc78fe0f307140878bb093b6
|
/cf/814/C/main.cpp
|
c4f75fadc04fff4caba2e3a9a23a305a25d2eda8
|
[] |
no_license
|
redeff/cmp
|
05603369f404cff25d168105b1f1c7a956fd07b8
|
8974bacf61b6c73d1cb5d3b5aa33c12af0d687d0
|
refs/heads/master
| 2021-05-08T01:10:47.542693 | 2019-10-13T22:19:32 | 2019-10-13T22:19:32 | 107,782,810 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 338 |
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define forn(i, a, b) for(ll i = a; i < b; ++i)
ll MOD = 1000000007; //10^9 + 7
template <typename T>
void get_vector(ll size){
vector<T> out;
forn(sahdfjhfsk, 0, size){
T temp;
cin >> temp;
out.push_back(temp);
}
return out;
}
int main(){
}
|
[
"[email protected]"
] | |
653e4fa1b6cdced997427cf8e64400d027db5869
|
b78c255d1c8b917c21bf689f5f9153d765fbe195
|
/dogpack/apps/2d/VlasovPoisson1d/TestConvergence1/InitSLState.cpp
|
6bf79e9f168c3f193bf044ac48fb8a72fa1d57c7
|
[] |
no_license
|
smoe1/ImplicitExplicit
|
8be586bed84b1a661e5fe71f5b063dcd406643fa
|
2b9a2d54110ca0f787d4252b9a8cc6d64b23b08d
|
refs/heads/master
| 2016-09-08T02:39:48.371767 | 2015-09-15T21:15:08 | 2015-09-15T21:15:08 | 41,374,555 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,332 |
cpp
|
///////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include "dogdefs.h"
#include "dog_math.h"
#include "DogParams.h"
#include "DogParamsCart2.h"
#include "SLState.h"
void FiniteDiff(int mestart, int meend, const dTensorBC3& q, dTensorBC3& qout);
void SetBndValues1D( dTensorBC3& q);
void L2Project_extra(const int istart,
const int iend,
const int jstart,
const int jend,
const int QuadOrder,
const int BasisOrder_qin,
const int BasisOrder_auxin,
const int BasisOrder_fout,
const dTensorBC4* qin,
const dTensorBC4* auxin,
dTensorBC4* fout,
void (*Func)(const dTensor2&,const dTensor2&,
const dTensor2&,dTensor2&, void* data),
void* data);
void ExtraSourceWrap(const dTensor2& xpts,
const dTensor2& NOT_USED_1,
const dTensor2& NOT_USED_2,
dTensor2& e,
void* data)
{
void ExtraSource(const dTensor2& xpts,
dTensor2& e,
void* data);
ExtraSource(xpts,e,data);
}
void InitSLState(
const dTensorBC4& q, const dTensorBC4& aux, SL_state& sl_state )
{
void ComputeElecField(double t, const dTensor2& node1d,
const dTensorBC4& qvals, dTensorBC3& Evals);
void ConvertQ2dToQ1d(const int &mopt, int istart, int iend,
const dTensorBC4& qin, dTensorBC3& qout);
void IntegrateQ1dMoment1(const dTensorBC4& q2d, dTensorBC3& q1d);
const int space_order = dogParams.get_space_order();
const int mx = q.getsize(1);
const int my = q.getsize(2);
const int meqn = q.getsize(3);
const int maux = aux.getsize(2);
const int kmax = q.getsize(4);
const int mbc = q.getmbc();
const int mpoints = space_order*space_order;
const int kmax1d = space_order;
const double tn = sl_state.tn;
//////////////////////// Compute Electric Field E(t) ////////////////////
// save 1d grid points ( this is used for poisson solve )
dTensorBC3 Enow(mx, meqn, kmax1d, mbc, 1);
ComputeElecField( tn, *sl_state.node1d, *sl_state.qnew, Enow);
//////////// Necessary terms for Et = -M1 + g(x,t) /////////////////////
dTensorBC3 M1(mx, meqn, kmax1d,mbc,1);
IntegrateQ1dMoment1(q, M1); // first moment
//////////// Necessary terms for Ett = 2*KE_x - rho*E + g_t - psi_u ///////
dTensorBC3 KE(mx, meqn, kmax1d,mbc,1);
void IntegrateQ1dMoment2(const dTensorBC4& q2d, dTensorBC3& q1d);
IntegrateQ1dMoment2(q, KE); // 1/2 * \int v^2 * f dv //
SetBndValues1D( KE );
SetBndValues1D( Enow );
SetBndValues1D( M1 );
// do something to compute KE_x ... //
dTensorBC3 gradKE(mx,2,kmax1d,mbc,1);
FiniteDiff( 1, 2, KE, gradKE ); // compute KE_x and KE_xx //
dTensorBC3 rho(mx,meqn,kmax1d,mbc,1);
dTensorBC3 prod(mx,meqn,kmax1d,mbc,1);
void IntegrateQ1d(const int mopt, const dTensorBC4& q2d, dTensorBC3& q1d);
void MultiplyFunctions(const dTensorBC3& Q1, const dTensorBC3& Q2,
dTensorBC3& qnew);
IntegrateQ1d( 1, q, rho );
MultiplyFunctions( rho, Enow, prod );
/////////////////////// Save E, Et, Ett, //////////////////////////////////
for( int i = 1; i <= mx; i++ )
for( int k = 1; k <= kmax1d; k ++ )
{
double E = Enow.get ( i, 1, k );
double Et = -M1.get ( i, 1, k ); // + g(x,t)
double Ett = -prod.get(i,1,k) + 2.0*gradKE.get(i,1,k); // + others //
sl_state.aux1d->set(i,2,1, k, E );
sl_state.aux1d->set(i,2,2, k, Et );
sl_state.aux1d->set(i,2,3, k, Ett );
}
///////////////////////////////////////////////////////////////////////////
// terms used for 4th order stuff ... //
// Ettt = -M3_xx + (2*E_x+rho)*M1 + 3*E*(M1)_x
dTensorBC3 tmp0(mx,2*meqn,kmax1d,mbc,1);
dTensorBC3 tmp1(mx,meqn,kmax1d,mbc,1);
// compute the third moment and its 2nd derivative
dTensorBC3 M3 (mx,meqn,kmax1d,mbc,1);
dTensorBC3 M3_x (mx,2*meqn,kmax1d,mbc,1);
void IntegrateQ1dMoment3(const dTensorBC4& q2d, dTensorBC3& q1d);
IntegrateQ1dMoment3(q, M3 );
SetBndValues1D( M3 );
FiniteDiff( 1, 2, M3, M3_x );
// Compute 2*Ex+rho //
FiniteDiff(1, 2*meqn, Enow, tmp0);
for( int i=1; i <= mx; i++ )
for( int k=1; k <= kmax1d; k++ )
{ tmp1.set(i,1,k, 2.0*tmp0.get(i,1,k) + rho.get(i,1,k) ); }
// compute (2Ex+rho) * M1
dTensorBC3 prod1(mx,meqn,kmax1d,mbc,1);
MultiplyFunctions( tmp1, M1, prod1 );
// compute M1_x and M1_xx
dTensorBC3 M1_x (mx,2*meqn,kmax1d,mbc,1);
FiniteDiff( 1, 2, M1, M1_x );
//compute 3*M1_x and E * (3*M1)_x
dTensorBC3 prod2(mx,meqn,kmax1d,mbc,1);
for( int i=1; i <= mx; i++ )
for( int k=1; k <= kmax1d; k++ )
{ tmp1.set(i, 1, k, 3.0*M1_x.get(i, 1, k) ); }
MultiplyFunctions( Enow, tmp1, prod2 );
/////////////////////// Save Ettt /////////////////////////////////////////
for( int i = 1; i <= mx; i++ )
for( int k = 1; k <= kmax1d; k ++ )
{
double Ettt = -M3_x.get(i,2,k) + prod1.get(i,1,k) + prod2.get(i,1,k);
sl_state.aux1d->set(i,2,4, k, Ettt );
}
///////////////////////////////////////////////////////////////////////////
if ( dogParams.get_source_term()>0 )
{
double* t_ptr = new double;
*t_ptr = tn;
// 2D Electric field, and 1D Electric Field
dTensorBC4* ExactE;
ExactE = new dTensorBC4(mx,1,4,kmax,mbc);
dTensorBC3* ExactE1d;
ExactE1d = new dTensorBC3(mx,4,kmax1d,mbc,1);
// Extra Source terms needed for the electric field
dTensorBC4* ExtraE;
ExtraE = new dTensorBC4(mx,1,4,kmax,mbc);
dTensorBC3* ExtraE1d;
ExtraE1d = new dTensorBC3(mx,4,kmax1d,mbc,1);
// Exact, electric field: (TODO - REMOVE THIS!)
// void ElectricField(const dTensor2& xpts, dTensor2& e, void* data);
// L2Project_extra(1-mbc, mx+mbc, 1, 1, space_order, -1, ExactE,
// &ElectricField, (void*)t_ptr );
// ConvertQ2dToQ1d(1, 1, mx, *ExactE, *ExactE1d);
// Extra Source terms:
void ExtraSourceWrap(const dTensor2& xpts,
const dTensor2& NOT_USED_1,
const dTensor2& NOT_USED_2,
dTensor2& e,
void* data);
L2Project_extra(1, mx, 1, 1, 20, space_order,
space_order, space_order,
&q, &aux, ExtraE, &ExtraSourceWrap, (void*)t_ptr );
ConvertQ2dToQ1d(1, 1, mx, *ExtraE, *ExtraE1d);
for( int i=1; i <= mx; i++ )
for( int k=1; k <= kmax1d; k++ )
{
// electric fields w/o source term parts added in //
double Et = sl_state.aux1d->get(i,2,2,k);
double Ett = sl_state.aux1d->get(i,2,3,k);
double Ettt = sl_state.aux1d->get(i,2,4,k);
// add in missing terms from previously set values //
sl_state.aux1d->set(i,2,2, k, Et + ExtraE1d->get(i,2,k) );
sl_state.aux1d->set(i,2,3, k, Ett + ExtraE1d->get(i,3,k) );
sl_state.aux1d->set(i,2,4, k, Ettt + ExtraE1d->get(i,4,k) );
// sl_state.aux1d->set(i,2,1, k, 0. );
// sl_state.aux1d->set(i,2,2, k, 0. );
// sl_state.aux1d->set(i,2,3, k, 0. );
// sl_state.aux1d->set(i,2,4, k, 0. );
// ADD IN EXACT ELECTRIC FIELD HERE:
// sl_state.aux1d->set(i,2,1, k, ExactE1d->get(i,1,k) );
// sl_state.aux1d->set(i,2,2, k, ExactE1d->get(i,2,k) );
// sl_state.aux1d->set(i,2,3, k, ExactE1d->get(i,3,k) );
// sl_state.aux1d->set(i,2,4, k, ExactE1d->get(i,4,k) );
}
delete ExactE;
delete ExactE1d;
delete t_ptr;
delete ExtraE;
delete ExtraE1d;
}
}
///////////////////////////////////////////////////////////////////////////////
// Periodic boundary conditions
void SetBndValues1D( dTensorBC3& q)
{
int i,m,ell;
double tmp;
const int melems = q.getsize(1);
const int meqn = q.getsize(2);
const int kmax = q.getsize(3);
const int mbc = q.getmbc();
for (ell=1; ell<=kmax; ell++)
{
// ***********************************************
// LEFT BOUNDARY
// ***********************************************
for (i=0; i>=(1-mbc); i--)
{
// q values
for (m=1; m<=meqn; m++)
{
tmp = q.get(i+melems,m,ell);
q.set(i,m,ell, tmp );
}
}
// ***********************************************
// ***********************************************
// RIGHT BOUNDARY
// ***********************************************
for (i=(melems+1); i<=(melems+mbc); i++)
{
// q values
for (m=1; m<=meqn; m++)
{
tmp = q.get(i-melems,m,ell);
q.set(i,m,ell, tmp );
}
}
// ***********************************************
}
}
/*
*
//////////////////////////////////////////////////////////////////////////////
// Compute q_x using finite differences of moments.
// Output is written to qout.
//
// qout(:,1,:) = q_x
// qout(:,2,:) = q_xx
//
//////////////////////////////////////////////////////////////////////////////
void FiniteDiff(int mestart, int meend, const dTensorBC3& q, dTensorBC3& qout)
{
const int mx = q.getsize(1);
const int meqn = q.getsize(2);
const int kmax = q.getsize(3);
const int mbc = q.getmbc();
const double dx = dogParamsCart2.get_dx();
const double two_dx = 2.0*dx;
const double dx2 = dx*dx;
for (int i=1; i<=mx; i++)
for( int me=mestart; me <= meend; me=me+2 )
{
dTensor1 dA ( 5 );
dTensor1 dA2( 5 );
dA.setall ( 0. );
dA2.setall ( 0. );
int ip1 = i+1;
int im1 = i-1;
int ic = i;
if (i<2)
{
im1 = im1+mx;
}
if (i>(mx-1))
{
ip1 = ip1-mx;
}
for (int k=1; k<=kmax; k++)
{
dA.set( k, (q.get(ip1,1,k)-q.get(im1,1,k))/two_dx );
dA2.set( k, (q.get(ip1,1,k)-2.0*q.get(ic,1,k)+q.get(im1,1,k))/dx2 );
}
switch(kmax)
{
case 5:
qout.set(i,me, 5, dA.get(5) );
qout.set(i,me+1,5, dA2.get(5) );
case 4:
qout.set(i,me, 4, dA.get(4) );
qout.set(i,me+1,4, dA2.get(4) );
case 3:
qout.set(i,me, 3, dA.get(3) - 14.0*sq5* dA.get(5) );
qout.set(i,me+1,3, dA2.get(3) - 7.0*sq5*dA2.get(5) );
case 2:
qout.set(i,me, 2, dA.get(2) - 10.0*sq7/sq3* dA.get(4) );
qout.set(i,me+1,2, dA2.get(2) - 5.0*sq7/sq3*dA2.get(4) );
case 1:
qout.set(i,me, 1, dA.get(1) - 2.0*sq5* dA.get(3) + 78.0* dA.get(5) );
qout.set(i,me+1,1, dA2.get(1) - sq5*dA2.get(3) + 11.0*dA2.get(5) );
break;
}
}
}
*/
|
[
"[email protected]"
] | |
54d4b46d14353b7601b4591d43d5a0d5e6755103
|
b8499de1a793500b47f36e85828f997e3954e570
|
/v2_3/build/Android/Debug/app/src/main/include/Fuse.LayoutParams.Flags.h
|
cf759b8222dbd73e461a8aa979a74b35c2063af3
|
[] |
no_license
|
shrivaibhav/boysinbits
|
37ccb707340a14f31bd57ea92b7b7ddc4859e989
|
04bb707691587b253abaac064317715adb9a9fe5
|
refs/heads/master
| 2020-03-24T05:22:21.998732 | 2018-07-26T20:06:00 | 2018-07-26T20:06:00 | 142,485,250 | 0 | 0 | null | 2018-07-26T20:03:22 | 2018-07-26T19:30:12 |
C++
|
UTF-8
|
C++
| false | false | 350 |
h
|
// This file was generated based on C:/Users/Vaibhav/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.9.0/LayoutParams.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Int.h>
namespace g{
namespace Fuse{
// private enum LayoutParams.Flags :14
uEnumType* LayoutParams__Flags_typeof();
}} // ::g::Fuse
|
[
"[email protected]"
] | |
b8cc72fd5d1efbc06adf9cc0b7d18d842e7968db
|
5f7f6d7e1ee62041b9a7b3a37904304e6df0bab6
|
/Carrot/src/Carrot/Renderer/Texture.h
|
1fc1377ce7e386a44bddad502a1624de1c925f7c
|
[
"Apache-2.0"
] |
permissive
|
AK04/game-engine
|
4a82bdca2d9892867084f86ec13fbb72270d0270
|
efa6641469c428efd8279e06bb8e575730684304
|
refs/heads/main
| 2023-06-06T01:54:31.399090 | 2021-06-21T08:34:25 | 2021-06-21T08:34:25 | 358,155,805 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 516 |
h
|
๏ปฟ#pragma once
#include <string>
#include "Carrot/Core/Core.h"
namespace Carrot {
class Texture
{
public:
virtual ~Texture() = default;
virtual uint32_t GetWidth() const = 0;
virtual uint32_t GetHeight() const = 0;
virtual void SetData(void* data, uint32_t size) = 0;
virtual void Bind(uint32_t slot = 0) const = 0;
};
class Texture2D : public Texture
{
public:
static Ref<Texture2D> Create(uint32_t width, uint32_t height);
static Ref<Texture2D> Create(const std::string& path);
};
}
|
[
"[email protected]"
] | |
58b7bf903364b3c5b71eee0f950fe69cc9c1ec7a
|
fbb8828913033070949aa50c3cca86ba6585ebc6
|
/Game.cpp
|
5d5de4598cf15c4c007c8dc27e380e5925c8b296
|
[] |
no_license
|
nooozu/onekick
|
4b4bb315f97956c9f71a9ebcc90e4ba53def1cce
|
9fc4fc18eedaa12de2e7bb8009c6c0ab872097ab
|
refs/heads/master
| 2020-03-24T20:36:56.256732 | 2018-07-31T08:48:55 | 2018-07-31T08:48:55 | 142,987,687 | 0 | 0 | null | null | null | null |
SHIFT_JIS
|
C++
| false | false | 5,410 |
cpp
|
#include "Game.h"
#include <ctime>
Game::Game(ISceneChanger* changer) : BaseScene(changer)
{
}
void Game::Initialize()
{
isGameFinished = false;
isRoundFinished = false;
if (!FontManager::Register(L"Font/SSF4_ABUKET.ttf")) { return; }
fontS = Font(40, L"SSF4 ABUKET", FontStyle::Outline);
fontS.changeOutlineStyle(TextOutlineStyle(Palette::Black, Palette::White, 3.0));
fontM = Font(80, L"SSF4 ABUKET", FontStyle::Outline);
fontM.changeOutlineStyle(TextOutlineStyle(Palette::Black, Palette::White, 3.0));
fontL = Font(120, L"SSF4 ABUKET", FontStyle::Outline);
fontL.changeOutlineStyle(TextOutlineStyle(Palette::Black, Palette::White, 3.0));
char_mgr = new CharManager(p1_fighter, p2_fighter);
round = 1;
p1_wins = 0, p2_wins = 0;
srand((unsigned)std::time(NULL));
int r = rand() % 3;
switch (r)
{
case 0:
background = Texture(Image(L"Image/background_00.png"));
break;
case 1:
//background = Texture(Image(L"Image/background_01.png"));
//break;
case 2:
background = Texture(Image(L"Image/Colosseum.jpg"));
break;
default:
background = Texture(Image(L"Image/background_00.png"));
break;
}
se_start = Sound(L"Sound/gong-played1.mp3");
bgm_00 = Sound(L"Sound/battle30.mp3");
bgm_00.setLoop(true);
bgm_00.setVolume(0.2);
bgm_00.play();
RoundReset();
}
void Game::Finalize()
{
delete char_mgr;
char_mgr = NULL;
}
void Game::RoundReset()
{
frame = 0;
end_time = 0;
time = 60 * GAME_TIME;
}
void Game::Update()
{
char_mgr->Update();
char_mgr->SetControl(false);
if (!isGameFinished) {
if (frame < 60) {
}
else if (frame < 120) {
if (frame == 100) {
se_start.play();
}
}
else {
char_mgr->SetControl(true);
time--;
if (time < 0) {
time = 0;
}
}
}
//ๅๅฉๅคๅฎ
switch (char_mgr->GetVictory()) {
case eP1:
p1_wins++;
break;
case eP2:
p2_wins++;
break;
}
//ๆ้ๅใ
if (time <= 0) {
isRoundFinished = true;
int p1_len = fabs(WW_X / 2 - char_mgr->GetP1().get_pos().x);
int p2_len = fabs(WW_X / 2 - char_mgr->GetP2().get_pos().x);
if (p1_len < p2_len) {
p1_wins++;
}
else {
p2_wins++;
}
}
//ใฉใฆใณใใชใปใใ
if (char_mgr->GetVictory() != eNone || time <= 0) {
char_mgr->Reset();
RoundReset();
round++;
isRoundFinished = false;
}
if (isRoundFinished) {
end_time++;
}
if (p1_wins >= GAME_ROUND || p2_wins >= GAME_ROUND) {
isGameFinished = true;
bgm_00.stop();
}
if (isGameFinished) {
GameOverUpdate();
}
frame++;
}
void Game::Draw()
{
background.draw();
if (time < 60 * 10) {
Line(WW_X / 2, 0, WW_X / 2, WW_Y).draw(5, Color(255, 0, 0, 255 * ((600 - time) / 600.0)));
}
if (isGameFinished) {
//f_title(L"GAME_OVER").drawCenter(640, 360);
if (p1_wins >= GAME_ROUND) {
fontL(L"P1 WINS").drawCenter(640, 360);
}
if (p2_wins >= GAME_ROUND) {
fontL(L"P2 WINS").drawCenter(640, 360);
}
}
else {
if (frame < 60) {
fontL(L"ROUND", round).drawCenter(640, 360);
}
else if (frame < 120) {
fontL(L"FIGHT").drawCenter(640, 360);
}
if (isRoundFinished && time <= 0) {
fontL(L"Draw").drawCenter(640, 360);
}
}
fontM(time / 60).drawCenter(640, 60);
double center_interval = 60;
{
//P1 ๅๅฉใซใฆใณใ
double x = 640;
double y = 80;
double r = 10;
for (int i = 0; i < GAME_ROUND; i++) {
Circle(x - center_interval * 1.3 - (i * (r + 15)), y, r).draw(Palette::Gray);
if (i + 1 <= p1_wins) {
Circle(x - center_interval * 1.3 - (i * (r + 15)), y, r * 0.8).draw(Palette::Red);
}
else {
Circle(x - center_interval * 1.3 - (i * (r + 15)), y, r * 0.8).draw();
}
}
}
{
//P2 ๅๅฉใซใฆใณใ
double x = 640;
double y = 80;
double r = 10;
for (int i = 0; i < GAME_ROUND; i++) {
Circle(x + center_interval * 1.3 + (i * (r + 15)), y, r).draw(Palette::Gray);
if (i + 1 <= p2_wins) {
Circle(x + center_interval * 1.3 + (i * (r + 15)), y, r * 0.8).draw(Palette::Red);
}
else {
Circle(x + center_interval * 1.3 + (i * (r + 15)), y, r * 0.8).draw();
}
}
}
char_mgr->Draw();
if (isGameFinished) {
GameOverDraw();
}
}
void Game::GameOverUpdate()
{
if (Input::KeyUp.clicked || Gamepad(0).povForward.clicked) {
select_count = 0;
}
if (Input::KeyDown.clicked || Gamepad(0).povBackward.clicked) {
select_count = 1;
}
if (Input::KeyEnter.clicked || Gamepad(0).button(0).clicked) {
switch (select_count)
{
case 0:
mSceneChanger->ChangeScene(eScene_Game);
break;
case 1:
mSceneChanger->ChangeScene(eScene_Menu);
break;
default:
break;
}
}
}
void Game::GameOverDraw()
{
int width = 200;
int height = 120;
int x = WW_X / 2 - width / 2;
int y = (WW_Y / 2 + 200) - height / 2;
RoundRect(x, y, width, height, 5).draw(Palette::Black);
width *= 0.95;
height *= 0.9;
x = WW_X / 2 - width / 2;
y = (WW_Y / 2 + 200) - height / 2;
RoundRect(x, y, width, height, 5).draw(Palette::Gray);
x = WW_X / 2;
y = (WW_Y / 2 + 200);
fontS(L"RePlay").drawCenter(x, y - 20, ((select_count == 0) ? Palette::Yellow : Palette::White));
fontS(L"Quit").drawCenter(x, y + 25, ((select_count == 1) ? Palette::Yellow : Palette::White));
}
|
[
"[email protected]"
] | |
c7fe9cf4d5ad04237a882600b089e266ec748663
|
9ec77255e72f19f8058064135e5260bd1e9886a3
|
/q/24.cpp
|
e83cb7a855eb015413786406f69e30874a0ee47c
|
[] |
no_license
|
a07458666/leetcode
|
b8abee6d338ddb983230643b1298561058f37015
|
fd608d4f3adfa505b0da88341aeee1bf7d5b5647
|
refs/heads/master
| 2022-11-29T20:33:37.943460 | 2020-08-14T03:12:24 | 2020-08-14T03:12:24 | 283,660,304 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 782 |
cpp
|
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
ListNode newHead(0);
newHead.next = head;
ListNode* currect = &newHead;
bool isSwap = true;
while (currect != NULL)
{
if (isSwap)
{
swapTwoNode(currect, currect->next);
}
isSwap = !isSwap;
currect = currect->next;
}
return newHead.next;
}
//ๅฐn1,n2็nextไบคๆ n1->t1 ---- n2->t2->??
void swapTwoNode(ListNode* n1, ListNode* n2)
{
if (n1->next == NULL || n2->next == NULL)
return;
swap(n1->next, n2->next);
if (n1->next->next == NULL)
{
n1->next->next = n2->next->next;
n2->next->next = NULL;
}
else if (n2->next->next == NULL)
{
n2->next->next = n1->next->next;
n1->next->next = NULL;
}
else
swap(n1->next->next, n2->next->next);
}
};
|
[
"[email protected]"
] | |
d8165aa1954c9deb5f8a645ccba9543c70a5cf27
|
e4ffd15e9cf875638883615256bc333404b3f248
|
/Mjehuric/main.cpp
|
35508a4df589f75b339fadc658475676c0f86597
|
[] |
no_license
|
Thomas-McKanna/Kattis
|
a49938663b4cc168eb7c51cd85f9d3d6a116c22c
|
0477ee7d39f694e98ca033dd32151cde11e7a9b1
|
refs/heads/master
| 2021-06-18T13:37:48.920524 | 2021-01-19T23:37:28 | 2021-01-19T23:37:28 | 149,032,585 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 730 |
cpp
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> p;
int n;
for (int i = 0; i < 5; i++) {
cin >> n;
p.push_back(n);
}
bool no_swaps;
for (size_t i = 0; i < p.size() - 1; i++) {
no_swaps = true;
for (size_t j = 0; j < p.size() - 1; j++) {
if (p.at(j) > p.at(j + 1)) {
no_swaps = false;
n = p.at(j);
p.at(j) = p.at(j + 1);
p.at(j + 1) = n;
for (auto it : p) {
cout << it << " ";
}
cout << endl;
}
}
if (no_swaps) {
break;
}
}
return 0;
}
|
[
"[email protected]"
] | |
d4aa8a845f3bdc7414ef6762bc0c3cc5f63525c7
|
23472c04d6ad2eaf7115dc6ecef5819d8e56db05
|
/tools/export/export.h
|
530e5a0b3c57fd78c6e4b645112e84d135048073
|
[] |
no_license
|
Veltarn/lunar
|
2eff19960ebdda0b7f144b15d0441f4582835578
|
2832d8b79095e61aaead351f48a3b4751a4be099
|
refs/heads/master
| 2021-01-25T08:54:58.490975 | 2015-09-20T15:08:35 | 2015-09-20T15:08:35 | 42,717,537 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 515 |
h
|
#ifndef EXPORT_H
#define EXPORT_H
#include <iostream>
#include <QDebug>
#include <QObject>
#include <QString>
#include <QtXml>
#include <QFile>
#include <QTextStream>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QMessageBox>
#include "../../db/database.h"
class Export : public QObject
{
Q_OBJECT
public:
explicit Export(QObject *parent = 0);
bool startExport(QString path, bool preserveApiLink = false);
signals:
public slots:
private:
Database m_database;
};
#endif // EXPORT_H
|
[
"[email protected]"
] | |
5fe8c8aabd7b0394323cb1b20b7d0716b675a8d6
|
a1112fc59fb5f3f7c1d8e6edd2f97688ff58a72e
|
/src/extSynthesis/manthanTest.cpp
|
bb9b383aaac77a28af9ebfe788f09d4a55713ed6
|
[
"MIT-Modern-Variant"
] |
permissive
|
NTU-ALComLab/elimssat
|
606c01533f8475cc7b8922e8caec758afe2459f5
|
04aea5d4ae846d247455a68267f55687d8db746d
|
refs/heads/main
| 2022-09-07T15:46:58.574310 | 2022-08-27T13:48:51 | 2022-08-27T13:48:51 | 436,710,202 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,859 |
cpp
|
#include "base/abc/abc.h"
#include "bdd/extrab/extraBdd.h"
#include "extSsatelim/ssatelim.h"
#include "synthesis.h"
#include "synthesisUtil.h"
extern "C" {
int Abc_NtkDarCec(Abc_Ntk_t *pNtk1, Abc_Ntk_t *pNtk2, int nConfLimit,
int fPartition, int fVerbose);
Abc_Ntk_t *Abc_NtkDC2(Abc_Ntk_t *pNtk, int fBalance, int fUpdateLevel,
int fFanout, int fPower, int fVerbose);
}
/**
* @brief perform exist quantified using BDD
*
*/
static DdNode *ExistQuantify(DdManager *dd, DdNode *bFunc,
Vec_Int_t *pPiIndex) {
Cudd_Ref(bFunc);
int *array = Vec_IntArray(pPiIndex);
int n = Vec_IntSize(pPiIndex);
DdNode *cube = Cudd_IndicesToCube(dd, array, n);
Cudd_Ref(cube);
DdNode *bRet = Cudd_bddExistAbstract(dd, bFunc, cube);
Cudd_Ref(bRet);
Cudd_RecursiveDeref(dd, cube);
Cudd_RecursiveDeref(dd, bFunc);
Cudd_Deref(bRet);
return bRet;
}
int manthanTest(char *pFileName, int fVerbose) {
ssat_solver *s = ssat_solver_new();
// char preprocess_cmd[128];
// sprintf(preprocess_cmd, "python3 wmcrewriting2.py %s tmp/temp.sdimacs", pFileName);
// system(preprocess_cmd);
ssat_Parser(s, pFileName);
Abc_Ntk_t *pNtkComp = Abc_NtkDup(s->pNtk);
// DdManager *dd =
// (DdManager *)Abc_NtkBuildGlobalBdds(s->pNtk, fBddSizeMax, 1, 1, 0, 0);
DdNode *bFunc = NULL;
bool useCadet = true;
if (!s->dd) {
// Abc_Print(1, "can't build BDD, choose a smaller instance for testing\n");
useCadet = true;
} else {
Abc_Print(1, "Build BDD success\n");
// bFunc = (DdNode *)Abc_ObjGlobalBdd(Abc_NtkPo(s->pNtk, 0));
useCadet = true;
}
for (int i = Vec_IntSize(s->pQuanType) - 1; i >= 0; i--) {
QuantifierType type = (QuantifierType)Vec_IntEntry(s->pQuanType, i);
Vec_Int_t *pScope = (Vec_Int_t *)Vec_PtrEntry(s->pQuan, i);
if (type == Quantifier_Exist) {
printf("number of exist variable = %d\n", pScope->nSize);
Abc_Ntk_t *pNtkNew;
if (!useCadet) {
bFunc = ExistQuantify(s->dd, s->bFunc, pScope);
pNtkNew = Abc_NtkDeriveFromBdd(s->dd, bFunc, NULL, NULL);
}
ssat_solver_existouter(s, pFileName);
int entry, index;
Vec_IntForEachEntry(pScope, entry, index) {
Vec_IntSetEntry(pScope, index, entry + 1);
}
// pNtkComp = Abc_NtkDC2(pNtkComp, 0, 0, 1, 0, 0);
if (useCadet) {
pNtkNew = cadetExistsElim(pNtkComp, pScope);
}
// Abc_Ntk_t* pNtkGolden = Abc_NtkStrash(s->pNtk, 0, 1, 0);
Abc_NtkShortNames(s->pNtk);
Abc_NtkShortNames(pNtkNew);
printf("checking if two circuits are equivalent...\n");
Abc_NtkDarCec(s->pNtk, pNtkNew, 100000, 0, 0);
Io_WriteAiger(pNtkNew, "test_exist.aig", 0, 0, 0);
Abc_NtkDelete(pNtkNew);
break;
}
}
Abc_NtkDelete(pNtkComp);
ssat_solver_delete(s);
return 0;
}
|
[
"[email protected]"
] | |
d79b2fc14a832f86c10e65ca2c081201f2adb9ee
|
19f7b73dfb3b41fb5375a058aa26ef6fa9a6f49c
|
/graph/bridge-and-cutpoint/graph-find-bridge.cpp
|
ec4909c798dc7543d08aad310729ce529a0332c2
|
[] |
no_license
|
Yoh0xFF/algorithm-collections
|
c43d1beff9bf25f2347624324c238e7431410ed6
|
58a7184c894030cf180f7164f5afbaaed9f9a1a5
|
refs/heads/master
| 2016-08-06T18:19:51.782094 | 2014-11-02T15:50:30 | 2014-11-02T15:50:30 | 19,120,941 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,093 |
cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
/*
O(n + m)
n - number of vertex
m - number of edges
*/
/*
test case
12 18
0 1
0 6
1 6
1 7
2 3
2 7
2 8
2 9
3 8
3 9
3 4
4 5
4 10
5 10
5 11
6 7
8 9
10 11
*/
/*
12 14
0 1
0 2
1 3
2 3
3 4
4 5
4 6
5 7
6 7
7 8
8 9
8 10
9 11
10 11
*/
class Graph
{
private:
int n, m, dfs_timer;
vector< vector<int> > graph;
vector<bool> used;
vector<int> t_in, f_up;
void debug();
void is_bridge(int v, int u);
void dfs_visit(int v, int p = -1);
public:
Graph();
void read_graph();
void find_bridges();
};
Graph::Graph(): n(0), m(0), dfs_timer(0) {}
void Graph::is_bridge(int v, int u)
{
cout << v << ' ' << u << endl;
}
void Graph::debug()
{
for (int i = 0; i < t_in.size(); ++i)
cout << t_in[i] << ' ';
cout << endl;
for (int i = 0; i < f_up.size(); ++i)
cout << f_up[i] << ' ';
cout << endl;
getchar();
}
void Graph::dfs_visit(int v, int p)
{
used[v] = true;
t_in[v] = f_up[v] = ++dfs_timer;
for (int i = 0; i < graph[v].size(); ++i)
{
int to = graph[v][i];
if (to == p) continue;
if (used[to])
f_up[v] = min(f_up[v], t_in[to]);
else
{
dfs_visit(to, v);
f_up[v] = min(f_up[v], f_up[to]);
if (f_up[to] > t_in[v]) is_bridge(v, to);
}
}
}
void Graph::read_graph()
{
cin >> n >> m;
vector<int> tmp;
for (int i = 0; i < n; ++i) graph.push_back(tmp);
int x(0), y(0);
for (int i = 0; i < m; ++i)
{
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x); // for undirected graphs
}
cout << endl;
getchar();
}
void Graph::find_bridges()
{
dfs_timer = 0;
used.assign(n, false);
t_in.assign(n, 0);
f_up.assign(n, 0);
for (int i = 0; i < n; ++i)
if (!used[i]) dfs_visit(i);
}
int main(int argc, char const *argv[])
{
Graph g;
g.read_graph();
g.find_bridges();
return 0;
}
|
[
"[email protected]"
] | |
9d4866a9a74bb781cc7c280c603e6aef17e13bff
|
3ccfe5694e622c7966440598f15fff8d167dbee5
|
/WindowInfo/WindowHandlePickerDlg.h
|
815cd8ae654f1af7b143907953ebe32dece3a410
|
[] |
no_license
|
EpistemikCpp/msProj
|
7dcc804640f2b4ad455296fb9d0566ae8e809d01
|
73b392ea25eb3f3b56118e2933501db0685410d1
|
refs/heads/master
| 2020-03-27T06:43:47.690776 | 2018-08-25T21:25:56 | 2018-08-25T21:25:56 | 146,130,581 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,952 |
h
|
// ==========================================================================
// File : WindowHandlePickerDlg.h
//
// Author : Marquet Mike
// [email protected]
//
// Last Modified : 21/02/2000
// By : Marquet Mike
// ==========================================================================
#if !defined(AFX_WINDOWHANDLEPICKERDLG_H__45D6A4E7_E46D_11D3_A10D_004005555C30__INCLUDED_)
#define AFX_WINDOWHANDLEPICKERDLG_H__45D6A4E7_E46D_11D3_A10D_004005555C30__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ==========================================================================
// Les Includes
// ==========================================================================
#include "HexaEdit.h"
#include "HandlePickerTitleTip.h"
/////////////////////////////////////////////////////////////////////////////
// CWindowHandlePickerDlg dialog
class CWindowHandlePickerDlg : public CDialog
{
public :
CWindowHandlePickerDlg(CWnd *pParent = NULL);
protected :
HICON m_hIcon;
HCURSOR m_hWindowFinderCursor;
HWND m_hLastHWND;
CBitmap m_WindowFinder1Bitmap;
CBitmap m_WindowFinder2Bitmap;
CHandlePickerTitleTip m_HandlePickerTitleTip;
void DisplayWindowInfo(HWND hWnd = NULL, BOOL bKeyboardInput = FALSE);
void InvertTracker(HWND hWnd);
void StartTracking(BOOL bFromTrayIcon, CPoint point);
void StopTracking();
public :
//{{AFX_DATA(CWindowHandlePickerDlg)
enum { IDD = IDD_WINDOWHANDLEPICKER_DIALOG };
CHexaEdit m_EDHandle;
BOOL m_CBAlwaysOnTop;
//}}AFX_DATA
protected :
//{{AFX_VIRTUAL(CWindowHandlePickerDlg)
public:
virtual BOOL DestroyWindow();
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
//}}AFX_VIRTUAL
//{{AFX_MSG(CWindowHandlePickerDlg)
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnPaint();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnChange_Handle();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnTrayMenu_ShowInterface();
afx_msg void OnTrayMenu_OptionsDlg();
afx_msg void OnTrayMenu_AboutBox();
afx_msg void OnCB_AlwaysOnTop();
//}}AFX_MSG
afx_msg LRESULT OnNotifyTaskBarIcon(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WINDOWHANDLEPICKERDLG_H__45D6A4E7_E46D_11D3_A10D_004005555C30__INCLUDED_)
|
[
"[email protected]"
] | |
d39169388f367b74578190bfb2256af3e5ee04fa
|
632da8ab5fb77c52e14d1a12712ad3cb3e71f6b0
|
/logcabin/Core/ProtoBuf.h
|
f6a37728d61efc117dfd7dc4aedfd5e93855d25c
|
[
"ISC",
"BSD-2-Clause"
] |
permissive
|
damlaren/RaftMonitor
|
09d4fc4d411a1f0482f23ac2fa5faa706b04f8ca
|
0736ec950c4c873419d855ad141171e70b724af8
|
refs/heads/master
| 2020-04-01T21:13:49.418344 | 2014-12-13T03:44:22 | 2014-12-13T03:44:22 | 26,423,850 | 5 | 2 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,797 |
h
|
/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <memory>
#include <string>
/**
* \file
* Utilities for dealing with protocol buffers.
*/
#ifndef LOGCABIN_CORE_PROTOBUF_H
#define LOGCABIN_CORE_PROTOBUF_H
namespace google {
namespace protobuf {
/**
* Equality for protocol buffers so that they can be used in EXPECT_EQ.
* This is useful for testing.
*/
bool operator==(const Message& a, const Message& b);
/**
* Inequality for protocol buffers so that they can be used in EXPECT_NE.
* This is useful for testing.
*/
bool operator!=(const Message& a, const Message& b);
// Equality and inequality between protocol buffers and their text format
// representations. These are useful for testing.
bool operator==(const Message& a, const std::string& b);
bool operator==(const std::string& a, const Message& b);
bool operator!=(const Message& a, const std::string& b);
bool operator!=(const std::string& a, const Message& b);
} // namespace google::protobuf
} // namespace google
namespace LogCabin {
namespace Core {
namespace ProtoBuf {
namespace Internal {
/// Helper for fromString template.
void fromString(const std::string& str, google::protobuf::Message& protoBuf);
} // namespace LogCabin::ProtoBuf::Internal
/**
* Create a protocol buffer message form a text format.
* This is useful for testing.
* \tparam ProtoBuf
* A derived class of ProtoBuf::Message.
* \param str
* The string representation of the protocol buffer message.
* Fields that are missing will not throw an error, but the resulting
* protocol buffer may be less useful.
* \return
* The parsed protocol buffer.
*/
template<typename ProtoBuf>
ProtoBuf
fromString(const std::string& str)
{
ProtoBuf protoBuf;
Internal::fromString(str, protoBuf);
return protoBuf;
}
/**
* Dumps a protocol buffer message.
* This is useful for debugging and for testing.
*
* \param protoBuf
* The protocol buffer message to dump out. It is safe to call this even
* if you haven't filled in all required fields, but the generated string
* will not be directly parse-able.
* \param forCopyingIntoTest
* If set to true, this will return a string in a format most useful for
* writing unit tests. You can basically copy and paste this from your
* terminal into your test file without manual processing. If set to false
* (default), the output will be nicer to read but harder to copy into a
* test file.
* \return
* Textual representation. This will be printable ASCII; binary will be
* escaped.
*/
std::string
dumpString(const google::protobuf::Message& protoBuf,
bool forCopyingIntoTest = false);
/**
* Copy the contents of a protocol buffer into a new one.
*/
std::unique_ptr<google::protobuf::Message>
copy(const google::protobuf::Message& protoBuf);
} // namespace LogCabin::Core::ProtoBuf
} // namespace LogCabin::Core
} // namespace LogCabin
#endif /* LOGCABIN_CORE_PROTOBUF_H */
|
[
"[email protected]"
] | |
0a0abdb9129132e52fe76aca584dddf54545c798
|
f87cdeeeb87a605aae9f7783864d822c01c59a24
|
/src/random.h
|
fdb9b61914753cd6ac5c75571ab8c5999397f369
|
[
"MIT"
] |
permissive
|
chinaOB/eleccoin
|
774f581eab7f0734a2b5c8817fc9ad3518a628ea
|
b2c08b538776b4276b6c8d0110af1115568049cf
|
refs/heads/master
| 2022-04-22T00:55:15.725364 | 2020-04-18T08:32:42 | 2020-04-18T08:32:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,495 |
h
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Eleccoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ELECCOIN_RANDOM_H
#define ELECCOIN_RANDOM_H
#include <crypto/chacha20.h>
#include <crypto/common.h>
#include <uint256.h>
#include <chrono> // For std::chrono::microseconds
#include <cstdint>
#include <limits>
/**
* Overall design of the RNG and entropy sources.
*
* We maintain a single global 256-bit RNG state for all high-quality randomness.
* The following (classes of) functions interact with that state by mixing in new
* entropy, and optionally extracting random output from it:
*
* - The GetRand*() class of functions, as well as construction of FastRandomContext objects,
* perform 'fast' seeding, consisting of mixing in:
* - A stack pointer (indirectly committing to calling thread and call stack)
* - A high-precision timestamp (rdtsc when available, c++ high_resolution_clock otherwise)
* - 64 bits from the hardware RNG (rdrand) when available.
* These entropy sources are very fast, and only designed to protect against situations
* where a VM state restore/copy results in multiple systems with the same randomness.
* FastRandomContext on the other hand does not protect against this once created, but
* is even faster (and acceptable to use inside tight loops).
*
* - The GetStrongRand*() class of function perform 'slow' seeding, including everything
* that fast seeding includes, but additionally:
* - OS entropy (/dev/urandom, getrandom(), ...). The application will terminate if
* this entropy source fails.
* - Bytes from OpenSSL's RNG (which itself may be seeded from various sources)
* - Another high-precision timestamp (indirectly committing to a benchmark of all the
* previous sources).
* These entropy sources are slower, but designed to make sure the RNG state contains
* fresh data that is unpredictable to attackers.
*
* - RandAddSeedSleep() seeds everything that fast seeding includes, but additionally:
* - A high-precision timestamp before and after sleeping 1ms.
* - (On Windows) Once every 10 minutes, performance monitoring data from the OS.
- - Once every minute, strengthen the entropy for 10 ms using repeated SHA512.
* These just exploit the fact the system is idle to improve the quality of the RNG
* slightly.
*
* On first use of the RNG (regardless of what function is called first), all entropy
* sources used in the 'slow' seeder are included, but also:
* - 256 bits from the hardware RNG (rdseed or rdrand) when available.
* - (On Windows) Performance monitoring data from the OS.
* - (On Windows) Through OpenSSL, the screen contents.
* - Strengthen the entropy for 100 ms using repeated SHA512.
*
* When mixing in new entropy, H = SHA512(entropy || old_rng_state) is computed, and
* (up to) the first 32 bytes of H are produced as output, while the last 32 bytes
* become the new RNG state.
*/
/**
* Generate random data via the internal PRNG.
*
* These functions are designed to be fast (sub microsecond), but do not necessarily
* meaningfully add entropy to the PRNG state.
*
* Thread-safe.
*/
void GetRandBytes(unsigned char* buf, int num) noexcept;
uint64_t GetRand(uint64_t nMax) noexcept;
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept;
int GetRandInt(int nMax) noexcept;
uint256 GetRandHash() noexcept;
/**
* Gather entropy from various sources, feed it into the internal PRNG, and
* generate random data using it.
*
* This function will cause failure whenever the OS RNG fails.
*
* Thread-safe.
*/
void GetStrongRandBytes(unsigned char* buf, int num) noexcept;
/**
* Sleep for 1ms, gather entropy from various sources, and feed them to the PRNG state.
*
* Thread-safe.
*/
void RandAddSeedSleep();
/**
* Fast randomness source. This is seeded once with secure random data, but
* is completely deterministic and does not gather more entropy after that.
*
* This class is not thread-safe.
*/
class FastRandomContext {
private:
bool requires_seed;
ChaCha20 rng;
unsigned char bytebuf[64];
int bytebuf_size;
uint64_t bitbuf;
int bitbuf_size;
void RandomSeed();
void FillByteBuffer()
{
if (requires_seed) {
RandomSeed();
}
rng.Keystream(bytebuf, sizeof(bytebuf));
bytebuf_size = sizeof(bytebuf);
}
void FillBitBuffer()
{
bitbuf = rand64();
bitbuf_size = 64;
}
public:
explicit FastRandomContext(bool fDeterministic = false) noexcept;
/** Initialize with explicit seed (only for testing) */
explicit FastRandomContext(const uint256& seed) noexcept;
// Do not permit copying a FastRandomContext (move it, or create a new one to get reseeded).
FastRandomContext(const FastRandomContext&) = delete;
FastRandomContext(FastRandomContext&&) = delete;
FastRandomContext& operator=(const FastRandomContext&) = delete;
/** Move a FastRandomContext. If the original one is used again, it will be reseeded. */
FastRandomContext& operator=(FastRandomContext&& from) noexcept;
/** Generate a random 64-bit integer. */
uint64_t rand64() noexcept
{
if (bytebuf_size < 8) FillByteBuffer();
uint64_t ret = ReadLE64(bytebuf + 64 - bytebuf_size);
bytebuf_size -= 8;
return ret;
}
/** Generate a random (bits)-bit integer. */
uint64_t randbits(int bits) noexcept {
if (bits == 0) {
return 0;
} else if (bits > 32) {
return rand64() >> (64 - bits);
} else {
if (bitbuf_size < bits) FillBitBuffer();
uint64_t ret = bitbuf & (~(uint64_t)0 >> (64 - bits));
bitbuf >>= bits;
bitbuf_size -= bits;
return ret;
}
}
/** Generate a random integer in the range [0..range). */
uint64_t randrange(uint64_t range) noexcept
{
--range;
int bits = CountBits(range);
while (true) {
uint64_t ret = randbits(bits);
if (ret <= range) return ret;
}
}
/** Generate random bytes. */
std::vector<unsigned char> randbytes(size_t len);
/** Generate a random 32-bit integer. */
uint32_t rand32() noexcept { return randbits(32); }
/** generate a random uint256. */
uint256 rand256() noexcept;
/** Generate a random boolean. */
bool randbool() noexcept { return randbits(1); }
// Compatibility with the C++11 UniformRandomBitGenerator concept
typedef uint64_t result_type;
static constexpr uint64_t min() { return 0; }
static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
inline uint64_t operator()() noexcept { return rand64(); }
};
/** More efficient than using std::shuffle on a FastRandomContext.
*
* This is more efficient as std::shuffle will consume entropy in groups of
* 64 bits at the time and throw away most.
*
* This also works around a bug in libstdc++ std::shuffle that may cause
* type::operator=(type&&) to be invoked on itself, which the library's
* debug mode detects and panics on. This is a known issue, see
* https://stackoverflow.com/questions/22915325/avoiding-self-assignment-in-stdshuffle
*/
template<typename I, typename R>
void Shuffle(I first, I last, R&& rng)
{
while (first != last) {
size_t j = rng.randrange(last - first);
if (j) {
using std::swap;
swap(*first, *(first + j));
}
++first;
}
}
/* Number of random bytes returned by GetOSRand.
* When changing this constant make sure to change all call sites, and make
* sure that the underlying OS APIs for all platforms support the number.
* (many cap out at 256 bytes).
*/
static const int NUM_OS_RANDOM_BYTES = 32;
/** Get 32 bytes of system entropy. Do not use this in application code: use
* GetStrongRandBytes instead.
*/
void GetOSRand(unsigned char *ent32);
/** Check that OS randomness is available and returning the requested number
* of bytes.
*/
bool Random_SanityCheck();
/**
* Initialize global RNG state and log any CPU features that are used.
*
* Calling this function is optional. RNG state will be initialized when first
* needed if it is not called.
*/
void RandomInit();
#endif // ELECCOIN_RANDOM_H
|
[
"[email protected]"
] | |
a03c0734d375988847f4a550180c1fc9925ee302
|
6a497b2945331bc29b212c17f7b32440e0b721f0
|
/src/FFmpegSample/FFmpegCODEC/stdafx.h
|
c09418af7e1e196bd03d08d9dbb4f565400910ad
|
[] |
no_license
|
dengchsh/FFmpeg-Sample
|
fe65acdd15d6f52d8cd903ec3b479514eaa6f769
|
ce1605ebccfb38b44100de6fb08db3db156e9dac
|
refs/heads/master
| 2021-05-30T09:33:34.529073 | 2016-01-22T10:35:58 | 2016-01-22T10:35:58 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,072 |
h
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <windows.h>
#include <shellapi.h>
#include <Shlwapi.h>
#include <conio.h> // For _kbhit() on Windows
#include <direct.h>
#include <map>
#include <vector>
#include <list>
#include <string>
#include "zcs_util.h"
#include "zcs_ParsingArgs.h"
using namespace std;
#ifdef _WIN32
//Windows
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfiltergraph.h"
#include "libavfilter/avcodec.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavformat/avformat.h>
#ifdef __cplusplus
};
#endif
#endif
// TODO: reference additional headers your program requires here
|
[
"[email protected]"
] | |
1094eb31bcafd3431f837d5838947c8ded2a4d7f
|
e35ba0a7253cb938b90e901e1cd0b3b689433e7e
|
/bcp_minigame_02/bin/windows/cpp/obj/include/com/minigloop/util/SoundManager.h
|
6ce9f00a02350bed21486d1a47312e5af69a126a
|
[] |
no_license
|
guarajeno/funbox
|
9fea33da9650a0a31f3f1f34865e838f8b68101b
|
7a0351b1669dd83f33f9f3959594f10b0439473f
|
refs/heads/master
| 2021-01-16T21:00:43.646249 | 2013-08-21T14:27:54 | 2013-08-21T14:27:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,324 |
h
|
#ifndef INCLUDED_com_minigloop_util_SoundManager
#define INCLUDED_com_minigloop_util_SoundManager
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS3(com,minigloop,util,SoundManager)
HX_DECLARE_CLASS2(native,events,ErrorEvent)
HX_DECLARE_CLASS2(native,events,Event)
HX_DECLARE_CLASS2(native,events,EventDispatcher)
HX_DECLARE_CLASS2(native,events,IEventDispatcher)
HX_DECLARE_CLASS2(native,events,TextEvent)
HX_DECLARE_CLASS2(native,media,Sound)
HX_DECLARE_CLASS2(native,media,SoundChannel)
namespace com{
namespace minigloop{
namespace util{
class SoundManager_obj : public hx::Object{
public:
typedef hx::Object super;
typedef SoundManager_obj OBJ_;
SoundManager_obj();
Void __construct();
public:
static hx::ObjectPtr< SoundManager_obj > __new();
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
~SoundManager_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_CSTRING("SoundManager"); }
static ::native::media::Sound _sound; /* REM */
static Array< ::String > _urls; /* REM */
static Array< ::String > _ids; /* REM */
static Array< ::native::media::Sound > _sounds; /* REM */
static Array< ::native::media::SoundChannel > _channels; /* REM */
static int _index; /* REM */
static Dynamic _callback; /* REM */
static ::native::media::SoundChannel _channel; /* REM */
static Void init( );
static Dynamic init_dyn();
static Void addSound( ::String url,::String id);
static Dynamic addSound_dyn();
static Void load( Dynamic __callback);
static Dynamic load_dyn();
static Void loadSound( ::native::events::Event e);
static Dynamic loadSound_dyn();
static Void onError( ::native::events::ErrorEvent e);
static Dynamic onError_dyn();
static ::native::media::Sound getSound( ::String id);
static Dynamic getSound_dyn();
static int getChannelId( ::String id);
static Dynamic getChannelId_dyn();
static Void play( ::String id,hx::Null< bool > loop);
static Dynamic play_dyn();
static Void stopAll( );
static Dynamic stopAll_dyn();
};
} // end namespace com
} // end namespace minigloop
} // end namespace util
#endif /* INCLUDED_com_minigloop_util_SoundManager */
|
[
"[email protected]"
] | |
5755b620594429366ab246777101853fffa1a958
|
977127d6ae53ae79a2fbcc7c034d84c516595d0e
|
/avt/Database/Ghost/avtLocalStructuredDomainBoundaries.h
|
af13694deca85deeded54716799cfdb9abfa3f7f
|
[] |
no_license
|
burlen/visit_vtk_7_src
|
51679fab1faf337e2e3f09f11c0da9515b049e94
|
9e3ce699b44803850208f003a46c0577dca1858a
|
refs/heads/master
| 2020-04-12T09:36:01.943093 | 2016-05-11T00:53:27 | 2016-05-11T00:53:27 | 51,111,375 | 1 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,464 |
h
|
/*****************************************************************************
*
* Copyright (c) 2000 - 2015, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/
// ************************************************************************* //
// avtLocalStructuredDomainBoundaries.h //
// ************************************************************************* //
#ifndef AVT_LOCAL_STRUCTURED_DOMAIN_BOUNDARIES_H
#define AVT_LOCAL_STRUCTURED_DOMAIN_BOUNDARIES_H
#include <avtStructuredDomainBoundaries.h>
#include <visitstream.h>
#include <vector>
class DATABASE_API avtLocalStructuredDomainBoundaryList
{
public:
avtLocalStructuredDomainBoundaryList(int domain_id,
int extents[6]);
avtLocalStructuredDomainBoundaryList(int *ptr);
avtLocalStructuredDomainBoundaryList(avtLocalStructuredDomainBoundaryList *lst);
virtual ~avtLocalStructuredDomainBoundaryList();
static void Destruct(void *);
void AddNeighbor(int neighbor_id,
int match,
int orientation[3],
int extents[6]);
int NumberOfNeighbors() const {return neighbors.size();}
static avtStructuredDomainBoundaries *GlobalGenerate(const std::vector<avtLocalStructuredDomainBoundaryList*> &lists);
void Print(ostream &os) const;
private:
int domainId;
int extents[6];
int Pack(int *ptr) const;
int PackedSize() const { return 8 + 11 * neighbors.size();}
static void GlobalGather(const std::vector<avtLocalStructuredDomainBoundaryList*> &local_lists,
std::vector<avtLocalStructuredDomainBoundaryList*> &out);
class DomainNeighbor
{
public:
DomainNeighbor(int neighbor_id,
int match,
int orientation[3],
int extents[6]);
DomainNeighbor(int *ptr);
DomainNeighbor(DomainNeighbor *nei);
virtual ~DomainNeighbor();
int PackedSize() const { return 11;}
int Pack(int *ptr) const;
void Print(ostream &os) const;
int neighborId;
int match;
int orientation[3];
int extents[6];
};
std::vector<DomainNeighbor *> neighbors;
};
#endif
|
[
"bonnell@18c085ea-50e0-402c-830e-de6fd14e8384"
] |
bonnell@18c085ea-50e0-402c-830e-de6fd14e8384
|
3edb45a424fb78fa18591dc9cbffeaac333a6bd6
|
884e57c0899457ed25d325a9ed50a18c4c5e9753
|
/socket/AsyncClient.h
|
edaa5a6dd49e2cc4f9e5a611071d5344437950de
|
[] |
no_license
|
liujin1992112/cocos2dx-socket
|
5953300b84d6ee1938c6c01c841ce225de40cfae
|
b8ed48b71462c63a38a7d5af28d2ba7af3974d9f
|
refs/heads/master
| 2021-08-21T20:55:44.149836 | 2017-11-29T02:08:56 | 2017-11-29T02:08:56 | null | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 2,543 |
h
|
#ifndef ASYNC_CLIENT_IPV4_H
#define ASYNC_CLIENT_IPV4_H
#include "IAsyncClient.h"
#include "DetailNetCommonHead.h"
#include "NetCommOperate.h"
#include "SocketOperThread.h"
#include <string>
#include <mutex>
using std::string;
namespace simplecreator {
class AsyncClient:public IAsyncClient
{
public:
AsyncClient();
virtual ~AsyncClient();
//ๅ้ๆฐๆฎ
virtual bool Send( const char *pData, unsigned int nLen );
//ๆฅๆถๆฐๆฎ๏ผๅฆๆ็ฌฌไธไธชๅๆฐไธบNULL๏ผ้ฃไนๅฏไปฅ่ทๅพๆถๅฐ็ๆฐๆฎ็้ฟๅบฆใๅฆๆ็ฌฌไธไธชๅๆฐไธบNULL๏ผ็ฌฌไบไธชๅๆฐไผ ๅ
ฅๆถๆๅฎไบ้ฟๅบฆ
//้ฃไนๆท่ดๆๅฎ้ฟๅบฆ็ๆฐๆฎ๏ผไฝไธไผๅคงไบ็ผๅฒๅบ็ๆๅคงๅผ๏ผ็ฌฌไบไธชๅๆฐๅฐไผ่ฟๅๅฎ้
ๆท่ด็้ฟๅบฆใ
//virtual bool Recv( char *pData, unsigned int &nLen );
//ๆญๅผ่ฟๆฅ
virtual bool Close();
//่ทๅพไธๆฌกๆไฝ้่ฏฏ
virtual int GetLastError();
//ๅค็๏ผๆฏๆฌก่ฐ็จๆญค้ฝไผ็ๆญฃ่ฟ่กๅค็,ๅฆๆ้ฝๆฒกๆ้่ฏฏ๏ผ้ฃไน่ฟๅtrue
virtual bool Process();
//่ฟๆฅ็IPๅ็ซฏๅฃ
virtual bool Connect( struct addrinfo *pAddrInfo, int nPort, bool bSyncMode=false );
virtual bool IsConnect();
virtual bool IsConnecting();
virtual void SetSingleRecvLen( unsigned int nLen );
virtual unsigned int GetSingleRecvLen();
//ๅฆๆๆฒกๆ่ฟๆฅ๏ผๅ่ฟๅ็ฉบๅญ็ฌฆไธฒ
virtual std::string GetHostIp();
protected:
// ่ฟๆฅๅฐๅ้ขๅค็
virtual bool PreConnect(struct addrinfo *pAddrInfo);
private:
void ClearFDSet();
void ResetFDSet();
void SetConnectResult( bool bSucceed );
// ๅๆญฅๆถๅ็บฟ็จ
virtual bool SendThread(bool* bWaitExit);
virtual bool RecvThread(bool* bWaitExit);
void OnSyncError(int nErrorCode, int nScene, bool bClose=false);
void CheckSyncSend();
// ๅๆญฅ้ปๅกๆจกๅผไธๅนถ่กๆถๅๅค็
virtual void StartSyncProcess();
// ๅๆญฅๅ้
virtual bool SyncSend(const char *pData, unsigned int nLen);
protected:
bool m_bConnect;
bool m_bConnecting;
bool m_bInit;
int m_nLastError;
NetCommonOperate m_netOperate;
CP_SOCKET m_sock;
string m_strHostIP;
private:
fd_set m_fdRead;
fd_set m_fdWrite;
fd_set m_fdError;
timeval m_timeOut;
string m_strRecvBuffer;
//string m_strSendBuffer;
bool m_bSyncMode;
SocketOperThread m_pSendThread;
SocketOperThread m_pRecvThread;
std::mutex m_pRecvMutex;
bool m_bHasRecv;
std::mutex m_pSendMutex;
std::string m_sSendCacheStr;
std::mutex m_pSocketMutex;
string m_strSingleRecv;
int m_nSingleRecvLen;
const static int nDefaultSingleRecvLen=4096; //้ป่ฎคไธๆฌกๆฅๆถ4Kๅคงๅฐ
};
}
#endif
|
[
"[email protected]"
] | |
6915b7c2770be66f590ca3edc5997a6cfe0f4339
|
53a82f3f1af0d44d3886cea7925966617cd8db5c
|
/UVA/13275/14041071_AC_0ms_0kB.cpp
|
2b2a9c504dd7a7a1c9d67deb58b3f25c2a93a426
|
[] |
no_license
|
kmtusher97/Solved-Problems
|
d24968a0b0fcb01ac3f13b4fb25ab6445c95d07b
|
6882df43d0bbb62169e8216665ea9cfb0d875ba7
|
refs/heads/master
| 2020-04-09T11:34:40.283984 | 2018-12-04T07:53:37 | 2018-12-04T07:53:37 | 160,312,784 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 971 |
cpp
|
/* BISMILLAHIR RAHMANIR RAHIM */
#include <bits/stdc++.h>
using namespace std;
#define FasterIO ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define sc scanf
#define pf printf
#define pb push_back
#define F first
#define S second
typedef long long intl;
typedef unsigned long long intu;
typedef queue<int> qi;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define MX_N 112345
const int MX = 112345;
bool chk( int year ) {
if (year % 400 == 0) return true;
else if(year % 100 == 0) return false;
else if(year % 4 == 0) return true;
else return false;
}
int main() {
int cases, caseno = 0;
sc("%d", &cases);
while( cases-- ) {
int d, m, y1, y2;
sc("%d %d %d %d", &d, &m, &y1, &y2);
pf("Case %d: ", ++caseno);
if( d==29 && m==2 ) {
int cnt = 0;
for(int i=y1+4; i<=y2; i+=4) {
if( chk(i) )cnt++;
}
pf("%d\n", cnt);
continue;
}
pf("%d\n", y2-y1);
}
return 0;
}
|
[
"[email protected]"
] | |
8cc7d54971b1579bd50700d3f1376dbe3ddf6374
|
8056cf5fd477d70d577181eefa59ce1d77140dce
|
/src/desktop/desktop.cpp
|
68fb868e770fd593151f44843d3ccfe1510885e7
|
[] |
no_license
|
geekprojects/awesome-desktop
|
bb80eb8b884271040be4c18789e964fb0e9eaf87
|
d02ce19a0708e5260103688d9138bfcd8aa73375
|
refs/heads/master
| 2023-02-24T06:19:02.499419 | 2021-01-28T13:05:04 | 2021-01-28T13:05:04 | 333,760,971 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,277 |
cpp
|
//
//
#include "desktop.h"
#include "screen.h"
#include "window.h"
#include <frontier/widgets/label.h>
using namespace std;
using namespace Awesome;
using namespace Frontier;
using namespace Geek;
using namespace Geek::Gfx;
DesktopApp::DesktopApp() : FrontierApp(L"Awesome Desktop")
{
}
DesktopApp::~DesktopApp() = default;
bool DesktopApp::init()
{
bool res;
res = FrontierApp::init();
if (!res)
{
return false;
}
((Frontier::AwesomeEngine*)getEngine())->unhandledEventSignal().connect(sigc::mem_fun(*this, &DesktopApp::handleEvent));
ClientConnection* client = getConnection();
InfoResponse* info = client->getInfo();
printf("ads-test: name=%s, vendor=%s\n", info->name, info->vendor);
printf("ads-test: numDisplays=%d\n", info->numDisplays);
m_backgroundImage = Surface::loadJPEG("../data/anteater.jpg");
unsigned int i;
for (i = 0; i < info->numDisplays; i++)
{
InfoDisplayRequest infoDisplayRequest;
infoDisplayRequest.display = i;
InfoDisplayResponse* response = (InfoDisplayResponse*)client->send(
&infoDisplayRequest,
sizeof(infoDisplayRequest));
printf("display %u: poa: %d, %d, size: %d, %d\n", i, response->x, response->y, response->width, response->height);
Screen* screen = new Screen(
this,
Geek::Rect(response->x, response->y, response->width, response->height),
response->scale);
screen->init();
m_screens.push_back(screen);
free(response);
}
delete info;
FrontierWindow* welcomeWindow = new FrontierWindow(this, L"Welcome", Frontier::WINDOW_NORMAL);
welcomeWindow->setContent(new Label(this, L"Welcome to the Awesome Desktop!"));
welcomeWindow->show();
return true;
}
void DesktopApp::handleEvent(Awesome::Event* event)
{
auto windowIt = m_windows.find(event->windowId);
Window* window = nullptr;
if (windowIt != m_windows.end())
{
window = windowIt->second;
}
log(DEBUG, "handleEvent: Window: %p", window);
if (window != nullptr)
{
window->handleEvent(event);
}
}
void DesktopApp::addWindow(Window* window)
{
m_windows.insert(make_pair(window->getMWindowId(), window));
}
|
[
"[email protected]"
] | |
10167dec4a47b5d799304443728fb1ec1be44982
|
021806922e8c30cee0481f121bb2524c30f2016b
|
/snippets/setithbit.cpp
|
c27003b0749b46a8874735b03d88f3b0c62c2546
|
[] |
no_license
|
apsknight/snippets
|
5d0aeb44dd32a63faf15c67b0be572be4baf87d1
|
596edd2fee92db41ab031e1ffc59cdd08ad529d8
|
refs/heads/master
| 2022-02-20T07:25:25.919361 | 2019-10-03T18:04:47 | 2019-10-04T08:11:04 | 81,497,666 | 2 | 2 | null | 2019-10-04T08:11:08 | 2017-02-09T21:41:09 |
C++
|
UTF-8
|
C++
| false | false | 50 |
cpp
|
void extract(int& n, int i) {
n = n | (1 << i);
}
|
[
"[email protected]"
] | |
3456f0b222da74ba5ab69421124fca5ff8e83386
|
a9c12a1da0794eaf9a1d1f37ab5c404e3b95e4ec
|
/CTPServer/CTPSubMarketDataSA.h
|
cbd8e83455e910fda1232c3a033d7c262d773c46
|
[] |
no_license
|
shzdtech/FutureXPlatform
|
37d395511d603a9e92191f55b8f8a6d60e4095d6
|
734cfc3c3d2026d60361874001fc20f00e8bb038
|
refs/heads/master
| 2021-03-30T17:49:22.010954 | 2018-06-19T13:21:53 | 2018-06-19T13:21:53 | 56,828,437 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 898 |
h
|
/***********************************************************************
* Module: CTPSubMarketDataSA.h
* Author: milk
* Modified: 2015ๅนด3ๆ6ๆฅ 20:11:00
* Purpose: Declaration of the class CTPSubMarketData
***********************************************************************/
#if !defined(__CTP_CTPSubMarketDataSA_h)
#define __CTP_CTPSubMarketDataSA_h
#include "../message/MessageHandler.h"
#include "ctpexport.h"
class CTP_CLASS_EXPORT CTPSubMarketDataSA : public MessageHandler
{
public:
dataobj_ptr HandleRequest(const uint32_t serialId, const dataobj_ptr& reqDO, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session);
dataobj_ptr HandleResponse(const uint32_t serialId, const param_vector& rawRespParams, IRawAPI* rawAPI, const IMessageProcessor_Ptr& msgProcessor, const IMessageSession_Ptr& session);
protected:
private:
};
#endif
|
[
"[email protected]"
] | |
7e4dfcb0a0f956fb62efff21d0eeb800d8a27335
|
586a03f4b93fd031f5eb677c7a43add038a4bc93
|
/src/main.cpp
|
e2bef69e5a18a7b3795d37274171ba12c4cb6270
|
[] |
no_license
|
kmz42/cudacomp
|
7d8b5e0f57cc15df4dbed0d573535f404025e221
|
ee519a126dfb595c4ddb14195322277c90d36e6a
|
refs/heads/master
| 2022-09-19T08:23:50.922986 | 2017-05-19T02:31:39 | 2017-05-19T02:31:39 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,372 |
cpp
|
/**
* @file main.cpp
*
* @brief Executable entrypoint
*
* @author Sean James <[email protected]>
*/
#include <defs.h>
#include <parser/parse.h>
#include <codegen/codegen.h>
#include <statics/statics.h>
#include <ast/astprint.h>
#include <options.h>
#include <iostream>
#include <fstream>
std::shared_ptr<ASTDeclSeqNode> append(
std::shared_ptr<ASTDeclSeqNode> to,
std::shared_ptr<ASTDeclSeqNode> from)
{
if (to == nullptr)
return from;
std::shared_ptr<ASTDeclSeqNode> decl = to;
while (decl->getTail() != nullptr)
decl = decl->getTail();
decl->setTail(from);
return to;
}
int main(int argc, char *argv[]) {
try {
// Parse arguments
parseArgs(argc, argv);
}
catch (std::runtime_error & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
return -1;
}
struct CCArgs *args = getOptions();
std::shared_ptr<ASTDeclSeqNode> ast = nullptr;
for (auto header : args->headers) {
if (args->verbose)
std::cout << "Parse '" << header << "'" << std::endl;
try {
std::shared_ptr<ASTDeclSeqNode> parsed = Parser::parse(header, true);
ast = append(ast, parsed);
}
catch (std::runtime_error & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
return -1;
}
catch (Parser::ParseException & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
return -1;
}
}
if (args->verbose)
std::cout << "Parse '" << args->in_file << "'" << std::endl;
try {
std::shared_ptr<ASTDeclSeqNode> parsed = Parser::parse(args->in_file, false);
ast = append(ast, parsed);
}
catch (std::runtime_error & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
return -1;
}
catch (Parser::ParseException & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
return -1;
}
std::shared_ptr<ModuleInfo> moduleInfo;
try {
moduleInfo = Statics::run(ast);
}
catch (Statics::StaticsException & except) {
std::cout << "\033[31;1m" << except.what() << "\033[0m" << std::endl;
if (args->print_ast) {
std::cout << "\033[31;1m" << "Partial AST:" << "\033[0m" << std::endl;
ASTPrint print(std::cout, true);
print.run(ast);
}
return -1;
}
if (args->print_ast) {
ASTPrint print(std::cout, true);
print.run(ast);
}
if (!args->emit_device) {
std::ofstream out(args->out_hfile, std::ios::out);
if (!out) {
std::cout << "\033[31;1m" << "Error opening " << args->out_dfile << "\033[0m" << std::endl;
return -1;
}
Codegen::codegen_tops(moduleInfo, ast, false, out);
out.close();
}
if (moduleInfo->hasCudaFunctions()) {
std::ofstream out(args->out_dfile, std::ios::out);
if (!out) {
std::cout << "\033[31;1m" << "Error opening " << args->out_dfile << "\033[0m" << std::endl;
return -1;
}
Codegen::codegen_tops(moduleInfo, ast, true, out);
out.close();
}
return 0;
}
|
[
"[email protected]"
] | |
bcccd8bf54b701301ac3924da7970ec67b2055da
|
cd8e140510f694df5f66b7acc0454ddc40e8be52
|
/kd_tree/FLANN/algorithms/all_indices.h
|
baf641443a667a8ab73f3544b6c6e73f32aaae20
|
[] |
no_license
|
HaoLi-China/Mobility-Reconstruction
|
721dc0c22ab1b4da12046b9bf6238267c1d20b95
|
7c4c02bffe0ff0a14e9f7189fad4c7ebf1404e86
|
refs/heads/master
| 2020-04-15T23:56:07.235922 | 2015-08-29T02:37:13 | 2015-08-29T02:37:13 | 40,639,055 | 1 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,643 |
h
|
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
* Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef FLANN_ALL_INDICES_H_
#define FLANN_ALL_INDICES_H_
#include "../general.h"
#include "nn_index.h"
#include "kdtree_index.h"
#include "kdtree_single_index.h"
#include "kmeans_index.h"
#include "composite_index.h"
#include "linear_index.h"
#include "hierarchical_clustering_index.h"
#include "lsh_index.h"
#include "autotuned_index.h"
#ifdef FLANN_USE_CUDA
#include "flann/algorithms/kdtree_cuda_3d_index.h"
#endif
namespace flann
{
/**
* enable_if sfinae helper
*/
template<bool, typename T = void> struct enable_if{};
template<typename T> struct enable_if<true,T> { typedef T type; };
/**
* disable_if sfinae helper
*/
template<bool, typename T> struct disable_if{ typedef T type; };
template<typename T> struct disable_if<true,T> { };
/**
* Check if two type are the same
*/
template <typename T, typename U>
struct same_type
{
enum {value = false};
};
template<typename T>
struct same_type<T,T>
{
enum {value = true};
};
#define HAS_MEMBER(member) \
template<typename T> \
struct member { \
typedef char No; \
typedef long Yes; \
template<typename C> static Yes test( typename C::member* ); \
template<typename C> static No test( ... ); \
enum { value = sizeof (test<T>(0))==sizeof(Yes) }; \
};
HAS_MEMBER(needs_kdtree_distance)
HAS_MEMBER(needs_vector_space_distance)
HAS_MEMBER(is_kdtree_distance)
HAS_MEMBER(is_vector_space_distance)
struct DummyDistance
{
typedef float ElementType;
typedef float ResultType;
template <typename Iterator1, typename Iterator2>
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
{
return ResultType(0);
}
template <typename U, typename V>
inline ResultType accum_dist(const U& a, const V& b, int) const
{
return ResultType(0);
}
};
/**
* Checks if an index and a distance can be used together
*/
template<template <typename> class Index, typename Distance, typename ElemType>
struct valid_combination
{
static const bool value = same_type<ElemType,typename Distance::ElementType>::value &&
(!needs_kdtree_distance<Index<DummyDistance> >::value || is_kdtree_distance<Distance>::value) &&
(!needs_vector_space_distance<Index<DummyDistance> >::value || is_kdtree_distance<Distance>::value || is_vector_space_distance<Distance>::value);
};
/*********************************************************
* Create index
**********************************************************/
template <template<typename> class Index, typename Distance, typename T>
inline NNIndex<Distance>* create_index_(flann::Matrix<T> data, const flann::IndexParams& params, const Distance& distance,
typename enable_if<valid_combination<Index,Distance,T>::value,void>::type* = 0)
{
return new Index<Distance>(data, params, distance);
}
template <template<typename> class Index, typename Distance, typename T>
inline NNIndex<Distance>* create_index_(flann::Matrix<T> data, const flann::IndexParams& params, const Distance& distance,
typename disable_if<valid_combination<Index,Distance,T>::value,void>::type* = 0)
{
return NULL;
}
template<typename Distance>
inline NNIndex<Distance>*
create_index_by_type(const flann_algorithm_t index_type,
const Matrix<typename Distance::ElementType>& dataset, const IndexParams& params, const Distance& distance)
{
typedef typename Distance::ElementType ElementType;
NNIndex<Distance>* nnIndex;
switch (index_type) {
case FLANN_INDEX_LINEAR:
nnIndex = create_index_<LinearIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_KDTREE_SINGLE:
nnIndex = create_index_<KDTreeSingleIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_KDTREE:
nnIndex = create_index_<KDTreeIndex,Distance,ElementType>(dataset, params, distance);
break;
//! #define this symbol before including flann.h to enable GPU search algorithms. But you have
//! to link libflann_cuda then!
#ifdef FLANN_USE_CUDA
case FLANN_INDEX_KDTREE_CUDA:
nnIndex = create_index_<KDTreeCuda3dIndex,Distance,ElementType>(dataset, params, distance);
break;
#endif
case FLANN_INDEX_KMEANS:
nnIndex = create_index_<KMeansIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_COMPOSITE:
nnIndex = create_index_<CompositeIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_AUTOTUNED:
nnIndex = create_index_<AutotunedIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_HIERARCHICAL:
nnIndex = create_index_<HierarchicalClusteringIndex,Distance,ElementType>(dataset, params, distance);
break;
case FLANN_INDEX_LSH:
nnIndex = create_index_<LshIndex,Distance,ElementType>(dataset, params, distance);
break;
default:
throw FLANNException("Unknown index type");
}
if (nnIndex==NULL) {
throw FLANNException("Unsupported index/distance combination");
}
return nnIndex;
}
}
#endif /* FLANN_ALL_INDICES_H_ */
|
[
"[email protected]"
] | |
93ac5e482cdcbdf3482b90b721c139a2fb417ebc
|
35908bc7f573a4b1ca99bb026f7bbe07261952cc
|
/Volume I/sgu137.cpp
|
0010be71ada98f3ca9ccc8270a83918aefdb07bd
|
[
"MIT"
] |
permissive
|
yuhc/sgu-solution
|
5257fe112b2d2e3ac55b1f0cf359b57269f69320
|
bc6f7d680da0b28c8e0aa83ea36c79f817a3c20f
|
refs/heads/master
| 2021-06-25T03:07:23.008745 | 2016-12-20T06:15:15 | 2016-12-20T06:15:15 | 32,255,735 | 0 | 3 | null | null | null | null |
UTF-8
|
C++
| false | false | 784 |
cpp
|
/* SGU ID: #137
* Type : Construction
* Author: Hangchen Yu
* Date : 02/15/2015
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
int main() {
int n, k;
scanf("%d%d", &n, &k);
bool bj[n];
int num, t;
for (int shift = 1; shift < n; shift++) {
memset(bj, false, sizeof(bj));
num = 0;
t = shift;
while (t != 0 && t != shift-1 && !bj[t]) {
bj[t] = true;
num++;
t = (t+shift)%n;
}
if (bj[n-1] && (k-num)%n == 0) break;
}
for (int i = 0; i < n-1; i++)
printf("%d ", (k-num)/n + (bj[i]?1:0));
printf("%d\n", (k-num)/n + (bj[n-1]?1:0));
return 0;
}
|
[
"[email protected]"
] | |
d8ed1705eaaec8883fd941fedb3d599148cc401c
|
9ee7bf8a1822d28b674a384dfde7ab47684ee5b6
|
/Darchangel/Source/Darchangel/WallJumpTriggerBox.h
|
12ab2643ce2a9f86e21ba2eda950619826fa9144
|
[] |
no_license
|
kahou0120424/Darchangel-Sector-8
|
f5b112e16e4556b2c440e0a542a028898c1346f2
|
1808dc19d9479945bdc840b53d8c7be76395252c
|
refs/heads/master
| 2023-05-24T05:40:09.155366 | 2020-12-18T11:02:13 | 2020-12-18T11:02:13 | 282,222,284 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 640 |
h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/TriggerBox.h"
#include "WallJumpTriggerBox.generated.h"
/**
*
*/
UCLASS()
class DARCHANGEL_API AWallJumpTriggerBox : public ATriggerBox
{
GENERATED_BODY()
protected:
virtual void BeginPlay() override;
public:
AWallJumpTriggerBox();
UFUNCTION()
void OnOverlapBegin(class AActor* OverlappedActor, AActor* OtherActor);
UFUNCTION()
void OnOverlapEnd(class AActor* OverlappedActor, AActor* OtherActor);
UPROPERTY(EditAnywhere, Category = "Chains Of Hell")
FVector JumpLocation;
};
|
[
"[email protected]"
] | |
3f552009480794e27f6a5fc645d8ee3467b2da6f
|
6aeccfb60568a360d2d143e0271f0def40747d73
|
/sandbox/maps/boost/maps/support/includes.hpp
|
9b1a529f82beb2df3ae500efab1a83b20b2d699f
|
[] |
no_license
|
ttyang/sandbox
|
1066b324a13813cb1113beca75cdaf518e952276
|
e1d6fde18ced644bb63e231829b2fe0664e51fac
|
refs/heads/trunk
| 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 |
C++
|
UTF-8
|
C++
| false | false | 747 |
hpp
|
//--
// Copyright (c) 2010-2011 Brian Smith
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/maps for documentation.
//--
#if !defined( BOOST_MAPS_SUPPORT_INCLUDES_HPP )
#define BOOST_MAPS_SUPPORT_INCLUDES_HPP
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/maps/support/expression.hpp>
#include <boost/maps/support/generic.hpp>
#include <boost/maps/support/bounds.hpp>
#include <utility>
#include <sstream>
#include <memory>
#include <stdexcept>
#include <algorithm>
#include <string.h>
#endif // BOOST_MAPS_SUPPORT_INCLUDES_HPP
|
[
"[email protected]"
] | |
80824c83512e3a3bc236750fea1454f6d3a7f182
|
55d560fe6678a3edc9232ef14de8fafd7b7ece12
|
/libs/math/reporting/performance/test_ellint_2c.cpp
|
35911cb722c45ed460a4607babd3613ea05baf66
|
[
"BSL-1.0"
] |
permissive
|
stardog-union/boost
|
ec3abeeef1b45389228df031bf25b470d3d123c5
|
caa4a540db892caa92e5346e0094c63dea51cbfb
|
refs/heads/stardog/develop
| 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 |
BSL-1.0
| 2020-11-17T19:50:36 | 2018-09-13T18:38:54 |
C++
|
UTF-8
|
C++
| false | false | 4,847 |
cpp
|
// Copyright John Maddock 2015.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifdef _MSC_VER
# pragma warning (disable : 4224)
#endif
#include <boost/math/special_functions/ellint_2.hpp>
#include <boost/array.hpp>
#include <boost/lexical_cast.hpp>
#include "../../test/table_type.hpp"
#include "table_helper.hpp"
#include "performance.hpp"
#include <iostream>
typedef double T;
#define SC_(x) static_cast<double>(x)
static const boost::array<boost::array<T, 2>, 10> data2 = { {
{ { SC_(-1.0), SC_(1.0) } },
{ { SC_(0.0), SC_(1.5707963267948966192313216916397514420985846996876) } },
{ { T(100) / 1024, SC_(1.5670445330545086723323795143598956428788609133377) } },
{ { T(200) / 1024, SC_(1.5557071588766556854463404816624361127847775545087) } },
{ { T(300) / 1024, SC_(1.5365278991162754883035625322482669608948678755743) } },
{ { T(400) / 1024, SC_(1.5090417763083482272165682786143770446401437564021) } },
{ { SC_(-0.5), SC_(1.4674622093394271554597952669909161360253617523272) } },
{ { T(-600) / 1024, SC_(1.4257538571071297192428217218834579920545946473778) } },
{ { T(-800) / 1024, SC_(1.2927868476159125056958680222998765985004489572909) } },
{ { T(-900) / 1024, SC_(1.1966864890248739524112920627353824133420353430982) } },
} };
int main()
{
#include "ellint_e_data.ipp"
add_data(data2);
add_data(ellint_e_data);
unsigned data_total = data.size();
screen_data([](const std::vector<double>& v){ return boost::math::ellint_2(v[0]); }, [](const std::vector<double>& v){ return v[1]; });
#if defined(TEST_LIBSTDCXX) && !defined(COMPILER_COMPARISON_TABLES)
screen_data([](const std::vector<double>& v){ return std::tr1::comp_ellint_2(v[0]); }, [](const std::vector<double>& v){ return v[1]; });
#endif
#if defined(TEST_GSL) && !defined(COMPILER_COMPARISON_TABLES)
screen_data([](const std::vector<double>& v){ return gsl_sf_ellint_Ecomp(v[0], GSL_PREC_DOUBLE); }, [](const std::vector<double>& v){ return v[1]; });
#endif
unsigned data_used = data.size();
std::string function = "ellint_2 (complete)[br](" + boost::lexical_cast<std::string>(data_used) + "/" + boost::lexical_cast<std::string>(data_total) + " tests selected)";
std::string function_short = "ellint_2 (complete)";
double time;
time = exec_timed_test([](const std::vector<double>& v){ return boost::math::ellint_2(v[0]); });
std::cout << time << std::endl;
#if !defined(COMPILER_COMPARISON_TABLES) && (defined(TEST_GSL) || defined(TEST_RMATH) || defined(TEST_LIBSTDCXX))
report_execution_time(time, std::string("Library Comparison with ") + std::string(compiler_name()) + std::string(" on ") + platform_name(), function, boost_name());
#endif
report_execution_time(time, std::string("Compiler Comparison on ") + std::string(platform_name()), function_short, compiler_name() + std::string("[br]") + boost_name());
//
// Boost again, but with promotion to long double turned off:
//
#if !defined(COMPILER_COMPARISON_TABLES)
if(sizeof(long double) != sizeof(double))
{
time = exec_timed_test([](const std::vector<double>& v){ return boost::math::ellint_2(v[0], boost::math::policies::make_policy(boost::math::policies::promote_double<false>())); });
std::cout << time << std::endl;
#if !defined(COMPILER_COMPARISON_TABLES) && (defined(TEST_GSL) || defined(TEST_RMATH) || defined(TEST_LIBSTDCXX))
report_execution_time(time, std::string("Library Comparison with ") + std::string(compiler_name()) + std::string(" on ") + platform_name(), function, boost_name() + "[br]promote_double<false>");
#endif
report_execution_time(time, std::string("Compiler Comparison on ") + std::string(platform_name()), function_short, compiler_name() + std::string("[br]") + boost_name() + "[br]promote_double<false>");
}
#endif
#if defined(TEST_LIBSTDCXX) && !defined(COMPILER_COMPARISON_TABLES)
time = exec_timed_test([](const std::vector<double>& v){ return std::tr1::comp_ellint_2(v[0]); });
std::cout << time << std::endl;
report_execution_time(time, std::string("Library Comparison with ") + std::string(compiler_name()) + std::string(" on ") + platform_name(), function, "tr1/cmath");
#endif
#if defined(TEST_GSL) && !defined(COMPILER_COMPARISON_TABLES)
time = exec_timed_test([](const std::vector<double>& v){ return gsl_sf_ellint_Ecomp(v[0], GSL_PREC_DOUBLE); });
std::cout << time << std::endl;
report_execution_time(time, std::string("Library Comparison with ") + std::string(compiler_name()) + std::string(" on ") + platform_name(), function, "GSL " GSL_VERSION);
#endif
return 0;
}
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.