AppDelegateBase.m 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160
  1. //
  2. // AppDelegateBase.m
  3. // iSales-UWAVER
  4. //
  5. // Created by Ray on 2018/8/9.
  6. // Copyright © 2018 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "AppDelegateBase.h"
  9. #import "UILabel+FontAppearance.h"
  10. #import "MainViewController.h"
  11. #import "RAPDFViewController.h"
  12. #import "ZipArchive.h"
  13. #import "DefaultAppearance.h"
  14. #import "OLDataProvider.h"
  15. #import "SelectUploadOrderViewController.h"
  16. #import "iSalesDB.h"
  17. #import "RANetwork.h"
  18. #import "NotificationNameCenter.h"
  19. #import "CustomerEditViewController.h"
  20. #import "CreateOrderViewController.h"
  21. #import "OrderDetailViewController.h"
  22. #import "AddressEditorViewController.h"
  23. #import "config.h"
  24. #import "RASingleton.h"
  25. #ifdef GOOGLE_ANALYTICS
  26. #import "Analytics.h"
  27. #import "GoogleAnalyst.h"
  28. #endif
  29. #import "ERPUtils.h"
  30. #import "RANetwork.h"
  31. #import "RASingleton.h"
  32. #ifdef BACKORDER_PROCESS
  33. #import "RAOrderEditorViewController.h"
  34. #endif
  35. #import "RAConvertor.h"
  36. //#import "config.h"
  37. #define UNZIP_OPEN_FAILED 0
  38. #define UNZIP_SUCCESS 1
  39. #define UNZIP_NO_SPACE 2
  40. #define UNZIP_FILE_DAMAGE 3
  41. @interface AppDelegateBase ()
  42. @end
  43. @implementation AppDelegateBase
  44. {
  45. #ifdef USE_SOFTSCAN
  46. DeviceInfo* _softScanDeviceInfo;
  47. #endif
  48. DeviceInfo* _deviceInfoToTrigger;
  49. NSMutableArray* _feedbackStack;
  50. id<ScannerEventsFeedback> _eventsFeedback;
  51. }
  52. @synthesize ScanApi;
  53. @synthesize ScanApiConsumer;
  54. @synthesize scanApiVersion;
  55. @synthesize price_hidden = _price_hidden;
  56. #pragma mark - Global Parameter
  57. //- (NSMutableDictionary *)globalParameters {
  58. // if (!_globalParameters) {
  59. // _globalParameters = [NSMutableDictionary dictionary];
  60. // }
  61. // return _globalParameters;
  62. //}
  63. //
  64. //- (void)setGlobalParameter:(id)param forKey:(NSString *)key {
  65. // if (param == nil || key == nil) {
  66. // return;
  67. // }
  68. // [self.globalParameters setObject:param forKey:key];
  69. //}
  70. //
  71. //- (id)globalParameterForKey:(NSString *)key {
  72. // if (key == nil) {
  73. // return nil;
  74. // }
  75. // return [self.globalParameters objectForKey:key];
  76. //}
  77. #pragma mark - Setter
  78. - (void)setUrgencyDic:(NSMutableDictionary *)urgencyDic {
  79. _urgencyDic = urgencyDic;
  80. [RASingleton.sharedInstance setGlobalParameter:_urgencyDic forKey:@"urgencyDic"];
  81. }
  82. - (void)setCan_see_price:(bool)can_see_price {
  83. _can_see_price = can_see_price;
  84. [RASingleton.sharedInstance setGlobalParameter:@(_can_see_price) forKey:@"can_see_price"];
  85. }
  86. - (void)setPrice_hidden:(bool)price_hidden {
  87. _price_hidden = price_hidden;
  88. [RASingleton.sharedInstance setGlobalParameter:@(_price_hidden) forKey:@"price_hidden"];
  89. #ifdef RA_NOTIFICATION
  90. [ActiveViewController Notify:@"" Message:RA_NOTIFICATION_UPDATE_PRICE];
  91. #else
  92. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  93. [avc showHidePrice];
  94. #endif
  95. }
  96. - (void)setOffline_mode:(bool)offline_mode {
  97. _offline_mode = offline_mode;
  98. [RASingleton.sharedInstance setGlobalParameter:@(_offline_mode) forKey:@"offline_mode"];
  99. }
  100. - (void)setUser:(NSString *)user {
  101. _user = user;
  102. RASingleton.sharedInstance.user = user;
  103. [RASingleton.sharedInstance setGlobalParameter:_user forKey:@"user"];
  104. }
  105. - (void)setUser_type:(long)user_type
  106. {
  107. _user_type = user_type;
  108. }
  109. - (void)setPassword:(NSString *)password {
  110. _password = password;
  111. [RASingleton.sharedInstance setGlobalParameter:_password forKey:@"password"];
  112. }
  113. #pragma mark - Normal
  114. -(void) set_priceHidden:(bool)price_hidden
  115. {
  116. [self setPrice_hidden:price_hidden];
  117. }
  118. -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
  119. {
  120. if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
  121. return;
  122. }
  123. #ifdef RA_NOTIFICATION
  124. [ActiveViewController Notify:@"ContactListViewController" Message:RA_NOTIFICATION_REFRESH_UI];
  125. //切换账号应该不需要刷新wishlist,此处如果刷新,会使wishlist新建订单自动添加出错。
  126. // [ActiveViewController Notify:@"WatchListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  127. #else
  128. [((MainViewController*)self.main_vc) reloadContact:false immediately:false];
  129. [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
  130. #endif
  131. _customerInfo=customerInfo;
  132. // DebugLog(@"%@",_customerInfo.class);
  133. // DebugLog(@"%@",customerInfo.class);
  134. // int count=customerInfo[@"count"];
  135. //assert(count==0);
  136. }
  137. -(void) set_main_button_panel
  138. {
  139. return;
  140. // dispatch_async(dispatch_get_main_queue(), ^{
  141. // if(self.main_vc==nil)
  142. // return;
  143. // MainViewController * main_vc= (MainViewController*)self.main_vc;
  144. // if(self.user_type==USER_ROLE_CUSTOMER)
  145. // {
  146. // main_vc.customer_bp.hidden=false;
  147. // main_vc.employee_bp.hidden = true;
  148. // }
  149. // else
  150. // {
  151. // main_vc.customer_bp.hidden=true;
  152. // main_vc.employee_bp.hidden = false;
  153. // }
  154. // });
  155. }
  156. //#ifdef SCANNER_ORDER
  157. //- (void)updateScanButton:(BOOL)enable
  158. //{
  159. // MainViewController * mainvc=(MainViewController * )self.main_vc;
  160. // mainvc.btnScan.enabled = enable;
  161. //}
  162. //#endif
  163. -(void) update_count_mark
  164. {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. if(self.main_vc==nil)
  167. return;
  168. MainViewController * main_vc= (MainViewController*)self.main_vc;
  169. //contact button
  170. if(self.user==nil)
  171. {
  172. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  173. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  174. main_vc.btnContact.hidden = YES;
  175. }
  176. else
  177. {
  178. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  179. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  180. if(self.customerInfo==nil)
  181. {
  182. // contact=@"No Name"; if(customerinfo==nil)
  183. // {
  184. contact=@"Select Contact";
  185. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  186. }
  187. else
  188. {
  189. if(contact==nil||contact.length==0)
  190. {
  191. contact=@"No Name";
  192. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  193. }
  194. else
  195. {
  196. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  197. }
  198. }
  199. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  200. if(contact.length>0)
  201. [arr_contact addObject:contact];
  202. if(customer.length>0)
  203. [arr_contact addObject:customer];
  204. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  205. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  206. }
  207. //cart
  208. if(self.user==nil||self.cart_count==0)
  209. {
  210. main_vc.label_ccount.hidden = true;
  211. main_vc.label_cccount.hidden=true;
  212. }
  213. else
  214. {
  215. NSString* strcount;
  216. if(self.cart_count>999)
  217. strcount=@"999+";
  218. else
  219. strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
  220. main_vc.label_ccount.text = strcount;
  221. if(strcount.length==1)
  222. main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
  223. if(strcount.length==2)
  224. main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
  225. if(strcount.length==3)
  226. main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
  227. if(strcount.length==4)
  228. main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
  229. main_vc.label_ccount.hidden = false;
  230. main_vc.label_cccount.text = strcount;
  231. if(strcount.length==1)
  232. main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
  233. if(strcount.length==2)
  234. main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
  235. if(strcount.length==3)
  236. main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
  237. if(strcount.length==4)
  238. main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
  239. main_vc.label_cccount.hidden = false;
  240. }
  241. //wishlist
  242. if(self.user==nil||self.wish_count==0)
  243. {
  244. main_vc.label_wcount.hidden = true;
  245. main_vc.label_cwcount.hidden = true;
  246. }
  247. else
  248. {
  249. NSString* strcount;
  250. if(self.wish_count>999)
  251. strcount=@"999+";
  252. else
  253. strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
  254. main_vc.label_wcount.text = strcount;
  255. if(strcount.length==1)
  256. main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
  257. if(strcount.length==2)
  258. main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
  259. if(strcount.length==3)
  260. main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
  261. if(strcount.length==4)
  262. main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
  263. main_vc.label_wcount.hidden = false;
  264. main_vc.label_cwcount.text = strcount;
  265. if(strcount.length==1)
  266. main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
  267. if(strcount.length==2)
  268. main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
  269. if(strcount.length==3)
  270. main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
  271. if(strcount.length==4)
  272. main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
  273. main_vc.label_cwcount.hidden = false;
  274. }
  275. });
  276. }
  277. -(void) closeOrder
  278. {
  279. self.order_code = nil;
  280. self.order_customer_id = nil;
  281. if(self.user_type!=USER_ROLE_CUSTOMER)
  282. {
  283. self.customerInfo = nil;
  284. self.contact_id = nil;
  285. }
  286. // [self SetMode:nil];
  287. // [self SetSo:nil];
  288. #ifdef RA_NOTIFICATION
  289. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  290. #else
  291. [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
  292. [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
  293. #endif
  294. // [self updateScanButton:false];
  295. }
  296. -(void) switchToPreviousVC
  297. {
  298. MainViewController * main_vc= (MainViewController*)self.main_vc;
  299. [main_vc switchToPreviousVC];
  300. }
  301. -(void) SetMode:(NSString*)mode1
  302. {
  303. __block NSString* blockmode= mode1;
  304. dispatch_async(dispatch_get_main_queue(), ^{
  305. if(self.offline_mode)
  306. blockmode =@"Regular Mode";
  307. if(self.main_vc==nil)
  308. return;
  309. MainViewController * main_vc= (MainViewController*)self.main_vc;
  310. if(self.user==nil)
  311. {
  312. NSString* title = [NSString stringWithFormat:@"Sign in"];
  313. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  314. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  315. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  316. main_vc.btnContact.hidden = YES;
  317. main_vc.labelMode.text=nil;
  318. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  319. return;
  320. }
  321. else
  322. {
  323. #ifndef SCANNER_ORDER
  324. main_vc.btnContact.hidden = NO;
  325. #endif
  326. if(self.user_type==USER_ROLE_CUSTOMER)
  327. {
  328. NSString* title = [NSString stringWithFormat:@"%@",self.user];
  329. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  330. main_vc.labelMode.text=nil;
  331. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  332. }
  333. else
  334. {
  335. if([blockmode isEqualToString:@"Regular Mode"])
  336. {
  337. self.mode=@"RM";
  338. NSString* title = self.user;
  339. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  340. main_vc.labelMode.text=self.mode;
  341. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  342. }
  343. else
  344. {
  345. self.mode=@"TM";
  346. NSString* title = self.user;
  347. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  348. main_vc.labelMode.text=self.mode;
  349. [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
  350. }
  351. }
  352. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  353. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  354. if(self.customerInfo==nil)
  355. {
  356. // contact=@"No Name"; if(customerinfo==nil)
  357. // {
  358. contact=@"Select Contact";
  359. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  360. }
  361. else
  362. {
  363. if(contact==nil||contact.length==0)
  364. {
  365. contact=@"No Name";
  366. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  367. }
  368. else
  369. {
  370. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  371. }
  372. }
  373. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  374. if(contact.length>0)
  375. [arr_contact addObject:contact];
  376. if(customer.length>0)
  377. [arr_contact addObject:customer];
  378. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  379. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  380. }
  381. });
  382. }
  383. -(void) SetSo:(NSString *)So
  384. {
  385. dispatch_async(dispatch_get_main_queue(), ^{
  386. if(self.main_vc==nil)
  387. return;
  388. MainViewController * main_vc= (MainViewController*)self.main_vc;
  389. if (self.user_type == USER_ROLE_CUSTOMER) {
  390. if (So == nil) {
  391. // 释放订单
  392. [RASingleton sharedInstance].currentOrderIsMerged = NO;
  393. }
  394. }
  395. if(self.user==nil)
  396. {
  397. // NSString* title = [NSString stringWithFormat:@"Sign in"];
  398. main_vc.labelSo.text=nil;
  399. return;
  400. }
  401. else
  402. {
  403. {
  404. if(So.length==0)
  405. main_vc.labelSo.text=nil;
  406. else
  407. {
  408. NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
  409. main_vc.labelSo.text=text;
  410. }
  411. }
  412. }
  413. });
  414. }
  415. //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  416. // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
  417. // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
  418. // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  419. // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
  420. // UINavigationController* navigationController = (UINavigationController*)rootViewController;
  421. // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  422. // } else if (rootViewController.presentedViewController) {
  423. // UIViewController* presentedViewController = rootViewController.presentedViewController;
  424. // return [self topViewControllerWithRootViewController:presentedViewController];
  425. // } else {
  426. // return rootViewController;
  427. // }
  428. //}
  429. //- (UIViewController*)topViewController {
  430. // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  431. //}
  432. //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  433. ////   // Get topmost/visible view controller
  434. // UIViewController *currentViewController = [self topViewController];
  435. //
  436. // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
  437. //
  438. // return UIInterfaceOrientationMaskPortrait;
  439. // }
  440. ////
  441. ////   // Only allow portrait (standard behaviour)
  442. // return UIInterfaceOrientationMaskAll;
  443. //}
  444. void UncaughtExceptionHandler(NSException *exception) {
  445. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  446. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  447. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  448. NSString *versionNum = @"";
  449. versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
  450. versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  451. /**
  452. * 获取异常崩溃信息
  453. */
  454. NSArray *callStack = [exception callStackSymbols];
  455. NSString *reason = [exception reason];
  456. NSString *name = [exception name];
  457. NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
  458. content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  459. NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
  460. if ([RASingleton sharedInstance].currentDB) {
  461. [iSalesDB close_db:[RASingleton sharedInstance].currentDB];
  462. }
  463. [iSalesDB execSql:sql];
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  466. [appDelegate writeUrgencyCache];
  467. });
  468. #ifdef SCANNER_ORDER
  469. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  470. [appDelegate saveUploadTasks];
  471. #endif
  472. }
  473. - (void)handleErrorLog {
  474. #ifdef SCANNER_ORDER
  475. return;
  476. #else
  477. __block NSMutableArray *err_array = [NSMutableArray array];
  478. [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  479. const char *version_char = (char *)sqlite3_column_text(stmt, 0);
  480. const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
  481. const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
  482. if (version_char == NULL)
  483. version_char = "";
  484. if (errlog_char == NULL)
  485. errlog_char = "";
  486. if (dateTime_char == NULL)
  487. dateTime_char = "";
  488. NSString *version_str = [NSString stringWithUTF8String:version_char];
  489. NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
  490. NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
  491. NSDictionary *err_dic = @{
  492. @"version" : version_str,
  493. @"errlog" : errlog_str,
  494. @"time" : dateTime_str
  495. };
  496. [err_array addObject:err_dic];
  497. }];
  498. if (err_array.count) {
  499. // 首先上传
  500. for (NSDictionary *err_dic in err_array) {
  501. NSString *version = [err_dic objectForKey:@"version"];
  502. NSString *errlog = [err_dic objectForKey:@"errlog"];
  503. NSString *time = [err_dic objectForKey:@"time"];
  504. NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
  505. // NSDictionary *ret = [RANetwork err_log:errlog result:result module:@"crash" code:0];
  506. dispatch_async(dispatch_get_main_queue(), ^{
  507. [RANetwork request_err_log:errlog result:result module:@"crash" code:0 completionHandler:^(NSMutableDictionary *result) {
  508. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  509. // 上传成功之后清除纪录
  510. if ([[result objectForKey:@"result"] integerValue] == 2) {
  511. [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
  512. }
  513. });
  514. }];
  515. });
  516. }
  517. }
  518. #endif
  519. }
  520. - (void)dealWithUrgencyFile {
  521. NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
  522. if (tmp_urgencyDic.allKeys.count > 2) {
  523. [self.urgencyDic removeAllObjects];
  524. [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
  525. // UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  526. NSString *user = [tmp_urgencyDic objectForKey:@"user"];
  527. if (![user isEqualToString:self.user]) {
  528. return;
  529. }
  530. BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
  531. if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
  532. return;
  533. }
  534. id count = [tmp_urgencyDic objectForKey:@"count"];
  535. int level_count = count ? (int)[count integerValue] : 0;
  536. if (!level_count) {
  537. return;
  538. }
  539. for (int i = 0; i < level_count; i++) {
  540. NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
  541. NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
  542. NSString *className = [urgencyDic objectForKey:@"class_name"];
  543. NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
  544. NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
  545. dispatch_async(dispatch_get_main_queue(), ^{
  546. if ([className isEqualToString:@"CustomerEditViewController"]) {
  547. // CustomerEditViewController
  548. NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
  549. BOOL new_customer = [urgencyDic objectForKey:@"new_customer"];
  550. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  551. [params setValue:contact_id forKey:@"contact_id"];
  552. CustomerEditViewController * cuseditVC =[[CustomerEditViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  553. cuseditVC.bnewcustomer=new_customer;
  554. cuseditVC.url_type = URL_RESTORE;
  555. cuseditVC.request_url= new_customer ? URL_NEW_CUSTOMER : URL_EDIT_CUSTOMER;
  556. cuseditVC.params = params;
  557. cuseditVC.content_data_download = restored_data;
  558. // cuseditVC.delegate=self;
  559. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  560. [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
  561. [mainVC.navigationController pushViewController:cuseditVC animated:false];
  562. } else if ([className isEqualToString:@"CreateOrderViewController"] || [className isEqualToString:@"RAOrderEditorViewController"]) {
  563. // CreateOrderViewController
  564. NSString *order_code = [urgencyDic objectForKey:@"order_code"];
  565. int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
  566. NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
  567. NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
  568. NSString *so = [urgencyDic objectForKey:@"order_so"];
  569. self.order_customer_id = order_customer_id;
  570. [RANetwork request_open_order:order_code completionHandler:^(NSMutableDictionary *result) {
  571. NSDictionary* order_json = result;
  572. // [waitalert dismissViewControllerAnimated:YES completion:nil];
  573. if([[order_json valueForKey:@"result"] intValue]==2)
  574. {
  575. self.order_code = order_code;
  576. self.order_status = order_status;
  577. [self SetSo:so];
  578. if (userType != USER_ROLE_CUSTOMER) {
  579. [RANetwork request_contactinfo:order_customer_id completionHandler:^(NSMutableDictionary *result) {
  580. self.customerInfo = [result[@"customerInfo"] mutableCopy];
  581. self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  582. }];
  583. // self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  584. //
  585. // self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  586. }
  587. #ifdef RA_NOTIFICATION
  588. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  589. #else
  590. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  591. [mainVC reloadOrder:true immediately:false];
  592. [mainVC reloadCart:true immediately:false];
  593. #endif
  594. }
  595. else
  596. {
  597. // MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  598. [RAUtils message_box:@"Open Order" message:[order_json valueForKey:@"err_msg"] completion:nil];
  599. }
  600. }];
  601. // 再place order
  602. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  603. if ([className isEqualToString:@"CreateOrderViewController"]) {
  604. CreateOrderViewController * orderinfoVC = [[CreateOrderViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  605. orderinfoVC.disable_dropdown_refresh=true;
  606. orderinfoVC.url_type = URL_RESTORE;
  607. orderinfoVC.request_url=URL_CARTDELIVERY;
  608. orderinfoVC.params = params;
  609. orderinfoVC.content_data_download = restored_data;
  610. orderinfoVC.resumeOrder = YES;
  611. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  612. [mainVC.navigationController pushViewController:orderinfoVC animated:true];
  613. }
  614. #ifdef BACKORDER_PROCESS
  615. else if ([className isEqualToString:@"RAOrderEditorViewController"]) {
  616. RAOrderEditorViewController *orderEditorVC = [[RAOrderEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  617. [orderEditorVC recoveryFromUrgencyDic:urgencyDic];
  618. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  619. [mainVC.navigationController pushViewController:orderEditorVC animated:YES];
  620. }
  621. #endif
  622. } else if ([className isEqualToString:@"AddressEditorViewController"]) {
  623. // AddressEditorViewController
  624. AddressEditorViewController * addressVC = [[AddressEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  625. addressVC.url_type = URL_RESTORE;
  626. addressVC.request_url=URL_ADDRESS_EDOTOR;
  627. NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
  628. params[@"is_subaction"]=@"true";
  629. addressVC.params = params;
  630. addressVC.content_data_download = restored_data;
  631. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  632. [mainVC.navigationController pushViewController:addressVC animated:true];
  633. }// class_name
  634. });
  635. }
  636. }
  637. }
  638. - (void)handleUrgencyFile {
  639. __weak typeof(self) weakself = self;
  640. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  641. if (weakself) {
  642. __strong typeof(weakself) strongself = weakself;
  643. [strongself dealWithUrgencyFile];
  644. }
  645. });
  646. }
  647. - (void)writeUrgencyCache {
  648. if (!self.user) {
  649. return;
  650. }
  651. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  652. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  653. // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
  654. [self.urgencyDic writeToFile:urgencyFile atomically:NO];
  655. // Place Order恢复是否能提交订单
  656. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
  657. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
  658. if ([RASingleton sharedInstance].currentOrderIsMerged && [RASingleton sharedInstance].permissions_submit_order) {
  659. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
  660. }
  661. }
  662. - (NSMutableDictionary *)readUrgencyCache {
  663. // 检查本地urgency文件,存在则加载进_urgencyDic
  664. NSFileManager *manager = [NSFileManager defaultManager];
  665. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  666. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  667. NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
  668. if ([manager fileExistsAtPath:urgencyFile]) {
  669. resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
  670. [manager removeItemAtPath:urgencyFile error:nil];
  671. }
  672. self.urgencyDic = [NSMutableDictionary dictionary];
  673. return resultDic;
  674. }
  675. - (void)initialExceptionHandler {
  676. if (exception_switch == 1) {
  677. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
  678. }
  679. }
  680. - (void)becomeObserver {
  681. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
  682. }
  683. - (void)dealloc {
  684. [[NSNotificationCenter defaultCenter] removeObserver:self];
  685. }
  686. #ifdef SCANNER_ORDER
  687. -(void) setAddress:(NSString *)address
  688. {
  689. _address = address;
  690. _uploadurl = [address stringByAppendingPathComponent:URL_SCAN_UPLOAD];// [NSString stringWithFormat:@"%@%@",address,URL_SCAN_UPLOAD];
  691. NSString * file = [NSString stringWithFormat:URL_SCAN_DOWNLOAD,[RADataProvider getSiteName]];
  692. _downloadurl =[address stringByAppendingPathComponent:file] ; // [NSString stringWithFormat:@"%@%@",address,URL_SCAN_DOWNLOAD];
  693. }
  694. #endif
  695. #ifdef GOOGLE_ANALYTICS
  696. - (void)setUpGoogleAnalytics {
  697. // 初始化Google Analytics
  698. NSError *configureError;
  699. [[GGLContext sharedInstance] configureWithError:&configureError];
  700. if (configureError) {
  701. DebugLog(@"congigure googleAnalytics error: %@",configureError);
  702. }
  703. GAI *gai = [GAI sharedInstance];
  704. gai.trackUncaughtExceptions = YES;
  705. id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
  706. // Enable IDFA collection.
  707. tracker.allowIDFACollection = YES;
  708. // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
  709. // 调试使用
  710. // gai.logger.logLevel = kGAILogLevelVerbose;
  711. // [[GAI sharedInstance] setDryRun:YES];
  712. //
  713. }
  714. #endif
  715. //-(void)test_descrypt
  716. //{
  717. // sqlite3 *db = [iSalesDB get_db];
  718. //
  719. // int result= [iSalesDB AddExFunction:db];
  720. //
  721. // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  722. // sqlite3_stmt * statement;
  723. //
  724. //
  725. // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  726. // {
  727. //
  728. //
  729. // while (sqlite3_step(statement) == SQLITE_ROW)
  730. // {
  731. //
  732. //
  733. // char *url = (char*)sqlite3_column_text(statement, 0);
  734. // if(url==nil)
  735. // url="";
  736. // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  737. // DebugLog(nsurl);
  738. //
  739. //
  740. //
  741. //
  742. // }
  743. // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  744. //
  745. //
  746. // sqlite3_finalize(statement);
  747. // }
  748. //
  749. // [iSalesDB close_db:db];
  750. //}
  751. //
  752. //-(void)test_descrypt1
  753. //{
  754. // sqlite3 *db = [iSalesDB get_db];
  755. //
  756. // int result= [iSalesDB AddExFunction:db];
  757. //
  758. // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
  759. //
  760. // [iSalesDB execSql:sqlindex];
  761. ////
  762. //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  763. //// sqlite3_stmt * statement;
  764. ////
  765. ////
  766. ////
  767. //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  768. //// {
  769. ////
  770. ////
  771. //// while (sqlite3_step(statement) == SQLITE_ROW)
  772. //// {
  773. ////
  774. ////
  775. //// char *url = (char*)sqlite3_column_text(statement, 0);
  776. //// if(url==nil)
  777. //// url="";
  778. //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  779. //// DebugLog(nsurl);
  780. ////
  781. ////
  782. ////
  783. ////
  784. //// }
  785. //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  786. ////
  787. ////
  788. //// sqlite3_finalize(statement);
  789. //// }
  790. //
  791. // [iSalesDB close_db:db];
  792. //}
  793. - (void)applicationWillResignActive:(UIApplication *)application
  794. {
  795. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  796. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  797. }
  798. - (void)applicationDidEnterBackground:(UIApplication *)application
  799. {
  800. [self download_offline:false checkdiskspace:false];
  801. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  802. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  803. #if defined(GOOGLE_ANALYTICS)
  804. NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
  805. self.forgroundDate = nil;
  806. [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
  807. #endif
  808. }
  809. - (void)applicationWillEnterForeground:(UIApplication *)application
  810. {
  811. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  812. }
  813. - (void)applicationDidBecomeActive:(UIApplication *)application
  814. {
  815. if(self.download_task!=nil)
  816. [self download_offline:true checkdiskspace:false];
  817. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  818. self.forgroundDate = [NSDate date];
  819. #ifdef SCANNER_ORDER
  820. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  821. configure.autoRemoveFinish = YES;
  822. }];
  823. if (!self.uploadManager) {
  824. self.uploadManager=[RAUploadManager sharedManager];
  825. }
  826. #endif
  827. }
  828. #ifdef SCANNER_ORDER
  829. -(RAUploadManager *)uploadManager
  830. {
  831. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  832. configure.autoRemoveFinish = YES;
  833. }];
  834. if (!_uploadManager) {
  835. _uploadManager=[RAUploadManager sharedManager];
  836. }
  837. return _uploadManager;
  838. }
  839. #endif
  840. -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
  841. {
  842. DebugLog(@"======================================");
  843. DebugLog(@"===== MEMORY WORRING ! ==========");
  844. DebugLog(@"======================================");
  845. }
  846. - (void)applicationWillTerminate:(UIApplication *)application
  847. {
  848. #ifdef SCANNER_ORDER
  849. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  850. [self saveUploadTasks];
  851. #endif
  852. }
  853. -(void) Logout
  854. {
  855. // 由于之前使用dispatch_async(dispatch_get_main_queue(), ^{}) 在用户切换时登出后刷新SideMenu User仍然显示
  856. dispatch_main_async_safe(^{
  857. MainViewController * main_vc= (MainViewController*)self.main_vc;
  858. [main_vc logoutOrder];
  859. [main_vc logoutCart];
  860. [main_vc logoutWish];
  861. [main_vc logoutContact];
  862. [main_vc logoutCategory];
  863. [main_vc logoutDocuments];
  864. [main_vc logoutPortfolio];
  865. #ifdef RA_NOTIFICATION
  866. [ActiveViewController Notify:@"SearchViewController" Message:RA_NOTIFICATION_CLEAR_DATA];
  867. #endif
  868. [main_vc hideMenu];
  869. [main_vc switchToHome];
  870. self.user = nil;
  871. self.password=nil;
  872. self.user_icon=nil;
  873. self.user_type = USER_ROLE_UNKNOWN;
  874. self.bLogin = false;
  875. self.contact_id=nil;
  876. self.customerInfo = nil;
  877. self.order_code = nil;
  878. [self.recent_model removeAllObjects];
  879. [self SetMode:nil];
  880. #ifdef SCANNER_ORDER
  881. self.available_price_group = nil;
  882. [RADataProvider default_price_group];
  883. #endif
  884. });
  885. }
  886. -(void)setOrder_code:(NSString *)order_code
  887. {
  888. _order_code = order_code;
  889. if(order_code==nil)
  890. NSLog(@"Clear order code");
  891. else
  892. NSLog(@"New order code %@",order_code);
  893. }
  894. - (void)checkLogin:(BOOL)reloadCurVC {
  895. [((MainViewController *)self.main_vc) checklogin:reloadCurVC];
  896. }
  897. //disable apn
  898. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  899. //{
  900. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  901. // DebugLog(@"regisger success:%@",deviceToken);
  902. //
  903. // //注册成功,将deviceToken保存到应用服务器数据库中
  904. //}
  905. #pragma mark - background download
  906. -(bool)isdownloading:(NSString*) file
  907. {
  908. return true;
  909. }
  910. -(long long)getcurrentLength:(int) taskidx
  911. {
  912. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  913. return position;
  914. }
  915. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  916. {
  917. //操作有两种,start stop;
  918. //结果有四种, wait , downloading, pause, finish
  919. dispatch_async(dispatch_get_main_queue(), ^{
  920. // debug;
  921. // NSString* file_name=[url lastPathComponent];
  922. //暂停<->开始转换
  923. // bool isdownloading = [self isdownloading:file_name];
  924. if (start)
  925. {//开始下载
  926. DebugLog(@"%d start",taskidx);
  927. self.current_task=taskidx;
  928. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  929. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  930. //
  931. //
  932. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  933. //
  934. // //设置请求头(GET)
  935. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  936. // [request setValue:range forHTTPHeaderField:@"Range"];
  937. //
  938. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  939. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  940. //设置请求头(GET)
  941. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  942. [request setValue:range forHTTPHeaderField:@"Range"];
  943. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  944. }else{ //暂停
  945. DebugLog(@"%d pause",taskidx);
  946. [self.connection cancel];
  947. self.connection = nil;
  948. }
  949. });
  950. }
  951. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order params:(NSMutableDictionary*) add_params
  952. {
  953. assert(add_params[@"user"]!=nil);
  954. assert(add_params[@"password"]!=nil);
  955. // assert(add_params[@"contact_id"]!=nil);
  956. [self add_downloadlog:@"Begin sync, please wait."];
  957. [self add_downloadlog:@"Prepare upload data."];
  958. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  959. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order params:add_params];
  960. NSString* upfile=upjson[@"file"];
  961. {
  962. NSData* data = [NSData dataWithContentsOfFile: upfile];
  963. // UIApplication * app = [UIApplication sharedApplication];
  964. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  965. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  966. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  967. if(add_params[@"user"]!=nil)
  968. [params setValue:add_params[@"user"] forKey:@"user"];
  969. // if(appDelegate.contact_id!=nil)
  970. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  971. if(add_params[@"password"]!=nil)
  972. [params setValue:add_params[@"password"] forKey:@"password"];
  973. #if TARGET_IPHONE_SIMULATOR//模拟器
  974. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  975. #elif TARGET_OS_IPHONE//真机
  976. UIDevice * dev = [UIDevice currentDevice];
  977. NSUUID* uuid =dev.identifierForVendor;
  978. [params setValue:uuid.UUIDString forKey:@"idfv"];
  979. #endif
  980. __weak typeof(self) weakSelf = self;
  981. [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
  982. if([[json valueForKey:@"result"] intValue]==2)
  983. {
  984. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  985. // 清理数据库要放入线程中执行
  986. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  987. if (out_of_stock_ids) {
  988. [RAUtils message_box:@"Warning" message:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] completion:nil];
  989. }
  990. [weakSelf add_downloadlog:@"Upload successful."];
  991. // [iSalesDB disable_trigger]
  992. [iSalesDB disable_trigger];
  993. NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  994. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  995. [iSalesDB execSql:@"delete from wishlist"];
  996. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  997. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  998. [iSalesDB execSql:@"delete from offline_portfolio"];
  999. [iSalesDB execSql:@"delete from offline_pdf"];
  1000. [OLDataProvider offline_clear_PDFCache];
  1001. NSString* contactMap = json[@"contactMap"];
  1002. if(contactMap.length>0)
  1003. {
  1004. NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
  1005. NSArray *keys= [contactjson allKeys];
  1006. //遍历keys
  1007. for(int i=0;i<[keys count];i++)
  1008. {
  1009. //得到当前key
  1010. NSString *key=[keys objectAtIndex:i];
  1011. //如果key不是pic,说明value是字符类型,比如name:Boris
  1012. NSString* value = [contactjson valueForKey:key];
  1013. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1014. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1015. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1016. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1017. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1018. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1019. }
  1020. }
  1021. // NSDictionary* contactjson= upjson[@"contact"];
  1022. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1023. // NSDictionary* orderjson= upjson[@"order"];
  1024. // [iSalesDB enable_trigger]
  1025. [iSalesDB enable_trigger];
  1026. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1027. [defaults removeObjectForKey:@"Forcedownload"];
  1028. [defaults setBool:true forKey:@"Forcedownload"];
  1029. [defaults synchronize];
  1030. dispatch_async(dispatch_get_main_queue(), ^{
  1031. //下载函数要从主线程调用
  1032. [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
  1033. });
  1034. });
  1035. }
  1036. else
  1037. {
  1038. [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
  1039. [weakSelf add_downloadlog:@"Sync canceled."];
  1040. [weakSelf.settingUI onSyncFinish];
  1041. }
  1042. } Progress:^(NSURLSessionTask *task, double progress) {
  1043. } DecryptHandler:nil];
  1044. }
  1045. return;
  1046. }
  1047. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1048. {
  1049. NSString *plistPath = [RAUtils get_config_path];
  1050. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1051. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1052. {
  1053. ver= nil;
  1054. [self add_downloadlog:@"App required a fully sync."];
  1055. }
  1056. if(self.downloading)
  1057. return;
  1058. self.downloading=true;
  1059. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1060. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1061. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1062. [RANetwork request_new_offline_ticket:ver useInternalAddress:false vid:pvid completionHandler:^(NSMutableDictionary *result) {
  1063. NSMutableDictionary* json= result;
  1064. if([json[@"result"] intValue]!=2)
  1065. {
  1066. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1067. [self.settingUI onSyncFinish];
  1068. // self.downloadlog=nil;
  1069. self.downloading=false;
  1070. return;
  1071. }
  1072. else
  1073. {
  1074. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1075. __block NSMutableDictionary* download_json=nil;
  1076. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1077. NSString* downSerial=[json valueForKey:@"downSerial"];
  1078. [defaults removeObjectForKey:@"downSerial"];
  1079. [defaults setValue:downSerial forKey:@"downSerial"];
  1080. [defaults synchronize];
  1081. // sleep(3);
  1082. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1083. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1084. // int count=0;
  1085. // // __block bool preparing = true;
  1086. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1087. // {
  1088. // sleep(RETRY_DELAY);
  1089. //
  1090. //
  1091. // count++;
  1092. //// download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1093. //
  1094. // [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1095. // download_json=result;
  1096. // }];
  1097. //
  1098. //
  1099. //
  1100. //
  1101. // }
  1102. [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1103. download_json=result;
  1104. if([download_json[@"result"] intValue]!=RESULT_TRUE)
  1105. {
  1106. [self add_downloadlog:download_json[@"err_msg"]];
  1107. [self add_downloadlog:@"Download Abort."];
  1108. dispatch_async(dispatch_get_main_queue(), ^{
  1109. // self.downloadlog=nil;
  1110. self.downloading=false;
  1111. [self.settingUI onSyncFinish];
  1112. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1113. [defaults removeObjectForKey:@"Forcedownload"];
  1114. [defaults setBool:true forKey:@"Forcedownload"];
  1115. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1116. // [defaults removeObjectForKey:@"downSerial"];
  1117. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1118. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1119. [defaults synchronize];
  1120. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1121. });
  1122. return;
  1123. }
  1124. //服务器准备数据完毕,进入处理数据逻辑。
  1125. if([download_json[@"request_count"] intValue]>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1126. {
  1127. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1128. dispatch_async(dispatch_get_main_queue(), ^{
  1129. // self.downloadlog=nil;
  1130. self.downloading=false;
  1131. });
  1132. dispatch_async(dispatch_get_main_queue(), ^{
  1133. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1134. });
  1135. [self.settingUI onSyncFinish];
  1136. return;
  1137. //一直没取到json,出错处理
  1138. }
  1139. else
  1140. {
  1141. if([download_json[@"count"] intValue]==0)
  1142. {
  1143. //没有找到更新包,当前是最新版本
  1144. [self add_downloadlog:@"You are up-to-date!"];
  1145. dispatch_async(dispatch_get_main_queue(), ^{
  1146. // self.downloadlog=nil;
  1147. self.downloading=false;
  1148. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1149. [defaults removeObjectForKey:@"Forcedownload"];
  1150. [defaults setBool:FALSE forKey:@"Forcedownload"];
  1151. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1152. // [defaults removeObjectForKey:@"downSerial"];
  1153. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1154. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1155. [defaults synchronize];
  1156. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1157. });
  1158. // dispatch_async(dispatch_get_main_queue(), ^{
  1159. //
  1160. // });
  1161. [self.settingUI onSyncFinish];
  1162. return;
  1163. }
  1164. else
  1165. {
  1166. [self add_downloadlog:@"Find a new version, downloading..."];
  1167. self.download_task = [download_json mutableCopy];
  1168. // self.download_task[@"abcdef"]=@"abcdef";
  1169. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1170. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1171. [self download_offline:true checkdiskspace:true];
  1172. return;
  1173. }
  1174. }
  1175. }];
  1176. }
  1177. }];
  1178. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1179. //
  1180. //
  1181. //
  1182. //
  1183. // NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1184. //
  1185. //
  1186. // if([json[@"result"] intValue]!=2)
  1187. // {
  1188. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1189. // [self.settingUI onSyncFinish];
  1190. // dispatch_async(dispatch_get_main_queue(), ^{
  1191. // // self.downloadlog=nil;
  1192. // self.downloading=false;
  1193. // });
  1194. // return;
  1195. // }
  1196. //
  1197. //
  1198. // dispatch_async(dispatch_get_main_queue(), ^{
  1199. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1200. // });
  1201. //
  1202. //
  1203. // NSMutableDictionary* download_json=nil;
  1204. //
  1205. // // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1206. // NSString* downSerial=[json valueForKey:@"downSerial"];
  1207. //
  1208. // [defaults removeObjectForKey:@"downSerial"];
  1209. // [defaults setValue:downSerial forKey:@"downSerial"];
  1210. //
  1211. // [defaults synchronize];
  1212. //
  1213. // // sleep(3);
  1214. // //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1215. //
  1216. //
  1217. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1218. // int count=0;
  1219. // // __block bool preparing = true;
  1220. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1221. // {
  1222. // sleep(RETRY_DELAY);
  1223. //
  1224. //
  1225. // count++;
  1226. // download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1227. //
  1228. //
  1229. //
  1230. //
  1231. // }
  1232. //
  1233. // //服务器准备数据完毕,进入处理数据逻辑。
  1234. // if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1235. // {
  1236. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1237. // dispatch_async(dispatch_get_main_queue(), ^{
  1238. // // self.downloadlog=nil;
  1239. // self.downloading=false;
  1240. // });
  1241. // dispatch_async(dispatch_get_main_queue(), ^{
  1242. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1243. // });
  1244. // [self.settingUI onSyncFinish];
  1245. // return;
  1246. // //一直没取到json,出错处理
  1247. // }
  1248. // else
  1249. // {
  1250. // if([download_json[@"count"] intValue]==0)
  1251. // {
  1252. // //没有找到更新包,当前是最新版本
  1253. // [self add_downloadlog:@"You are up-to-date!"];
  1254. // dispatch_async(dispatch_get_main_queue(), ^{
  1255. // // self.downloadlog=nil;
  1256. // self.downloading=false;
  1257. // });
  1258. // dispatch_async(dispatch_get_main_queue(), ^{
  1259. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1260. // });
  1261. // [self.settingUI onSyncFinish];
  1262. // return;
  1263. // }
  1264. // else
  1265. // {
  1266. // [self add_downloadlog:@"Find a new version, downloading..."];
  1267. // self.download_task = [download_json mutableCopy];
  1268. // // self.download_task[@"abcdef"]=@"abcdef";
  1269. // long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1270. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1271. // [self download_offline:true checkdiskspace:true];
  1272. // return;
  1273. // }
  1274. //
  1275. // }
  1276. //
  1277. // });
  1278. }
  1279. #ifdef SCANNER_ORDER
  1280. //- (NSString *)price0_name
  1281. //{
  1282. // if(_price0_name.length==0)
  1283. // {
  1284. // return @"DDP";
  1285. // }
  1286. // else
  1287. // return _price0_name;
  1288. //}
  1289. //- (NSString *)price1_name
  1290. //{
  1291. // if(_price1_name.length==0)
  1292. // {
  1293. // return @"Unit Price";
  1294. // }
  1295. // else
  1296. // return _price1_name;
  1297. //}
  1298. //- (NSString *)price2_name
  1299. //{
  1300. // if(_price2_name.length==0)
  1301. // {
  1302. // return @"Special";
  1303. // }
  1304. // else
  1305. // return _price2_name;
  1306. //}
  1307. //- (NSString *)price3_name
  1308. //{
  1309. // if(_price3_name.length==0)
  1310. // {
  1311. // return @"Net Price";
  1312. // }
  1313. // else
  1314. // return _price3_name;
  1315. //}
  1316. #endif
  1317. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1318. {
  1319. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1320. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1321. if(forcedownload|| ver==nil)
  1322. {
  1323. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1324. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1325. syncVC.action_string=@"Download";
  1326. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1327. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1328. navi.modalInPresentation = true;
  1329. navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
  1330. [parent presentViewController:navi animated:YES completion:^{
  1331. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1332. DebugLog(@"about present.........");
  1333. // self.btop = false;
  1334. // <#code#>
  1335. }];
  1336. }
  1337. else
  1338. {
  1339. NSArray* arr_order=nil;
  1340. arr_order=[OLDataProvider enumOfflineOrder];
  1341. // if(arr_order.count>0)
  1342. // {
  1343. //
  1344. // {
  1345. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1346. // vc.returnValue = ^(NSArray* SelectedOrder){
  1347. //
  1348. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1349. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1350. // syncVC.action_string=@"Download";
  1351. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1352. //
  1353. //
  1354. //
  1355. //
  1356. //
  1357. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1358. //
  1359. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1360. // [parent presentViewController:navi animated:YES completion:^{
  1361. //
  1362. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1363. //
  1364. // DebugLog(@"about present.........");
  1365. //
  1366. // // self.btop = false;
  1367. // // <#code#>
  1368. // }];
  1369. // };
  1370. //
  1371. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1372. //
  1373. //
  1374. //
  1375. //
  1376. //
  1377. //
  1378. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1379. // [parent presentViewController:navi animated:YES completion:^{
  1380. //
  1381. //
  1382. // }];
  1383. // }
  1384. //
  1385. //
  1386. // }
  1387. // else
  1388. // {
  1389. NSMutableDictionary* add_params=[NSMutableDictionary new];
  1390. add_params[@"user"]=self.user;
  1391. add_params[@"password"]=self.password;
  1392. add_params[@"contact_id"]=self.contact_id;
  1393. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order params:add_params];
  1394. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1395. syncVC.action_string=@"Download";
  1396. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1397. navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
  1398. [parent presentViewController:navi animated:YES completion:^{
  1399. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1400. DebugLog(@"about present.........");
  1401. // self.btop = false;
  1402. // <#code#>
  1403. }];
  1404. // }
  1405. }
  1406. }
  1407. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1408. {
  1409. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1410. if(start)
  1411. {
  1412. dispatch_async(dispatch_get_main_queue(), ^{
  1413. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1414. });
  1415. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1416. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1417. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1418. long long needsize = size+500;
  1419. if(needsize>freespace &&checkdiskspace)
  1420. {
  1421. //size not enough.
  1422. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1423. [self add_downloadlog:space];
  1424. [self.settingUI onSyncFinish];
  1425. return ;
  1426. }
  1427. NSString* temp = NSTemporaryDirectory();
  1428. NSString * ver = self.download_task[@"ver"];
  1429. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1430. //创建版本临时目录
  1431. NSFileManager* fileManager = [NSFileManager defaultManager];
  1432. BOOL bdir=YES;
  1433. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1434. {
  1435. NSError *error = nil;
  1436. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1437. if(!bsuccess)
  1438. DebugLog(@"Create temp folder failed");
  1439. // if(bsuccess)
  1440. // {
  1441. // sqlite3 *db = [self get_db];
  1442. //
  1443. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1444. // [iSalesDB close_db:db];
  1445. // }
  1446. }
  1447. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1448. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1449. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1450. {
  1451. NSError *error = nil;
  1452. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1453. if(!bsuccess)
  1454. DebugLog(@"Create cache folder failed");
  1455. }
  1456. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1457. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1458. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1459. // {
  1460. //
  1461. // NSError *error = nil;
  1462. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1463. //
  1464. // if(!bsuccess)
  1465. // DebugLog(@"Create resource folder failed");
  1466. //
  1467. // }
  1468. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1469. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1470. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1471. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1472. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1473. NSError *error = nil;
  1474. bdir=NO;
  1475. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1476. {
  1477. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1478. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1479. {
  1480. DebugLog(@"copy database failed");
  1481. }
  1482. }
  1483. bdir=YES;
  1484. error=nil;
  1485. int count = [[self.download_task valueForKey:@"count"] intValue];
  1486. bool alldone=true;
  1487. bool trouble=false;
  1488. bool response = false;
  1489. for (int i = 0;i<count;i++)
  1490. {
  1491. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1492. NSString* url = [itemjson valueForKey:@"url"];
  1493. NSString* type = [itemjson valueForKey:@"type"];
  1494. {
  1495. #ifdef DEBUG
  1496. //调试模式下跳过下载图片
  1497. if([type isEqualToString:@"img"])
  1498. {
  1499. itemjson[@"status"]=@"finish";
  1500. continue;
  1501. }
  1502. #endif
  1503. }
  1504. NSString* status = itemjson[@"status"];
  1505. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1506. if(! [status isEqualToString:@"finish"])
  1507. {
  1508. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1509. {
  1510. [self handle_download:url start:start type:type taskid:i];
  1511. alldone=false;
  1512. break;
  1513. }
  1514. else
  1515. {
  1516. alldone=false;
  1517. trouble=true;
  1518. response = [itemjson[@"response"] boolValue];
  1519. break;
  1520. }
  1521. }
  1522. }
  1523. if(trouble)
  1524. {
  1525. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1526. if(response==false)
  1527. {
  1528. msg=@"Cannot connect to server, please check your network.";
  1529. }
  1530. [self add_downloadlog:msg];
  1531. dispatch_async(dispatch_get_main_queue(), ^{
  1532. // self.downloadlog=nil;
  1533. self.downloading=false;
  1534. });
  1535. [self.settingUI onSyncFinish];
  1536. }
  1537. else if(alldone)
  1538. {
  1539. [self add_downloadlog:@"Finalizing download..."];
  1540. //全部下载完成;
  1541. //写入当前版本
  1542. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1543. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1544. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1545. NSString* ver= self.download_task[@"ver"];
  1546. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1547. NSString *cachefolder = [paths objectAtIndex:0];
  1548. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1549. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1550. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1551. {
  1552. DebugLog(@"move image folder failed");
  1553. [self add_downloadlog:@"move image folder failed"];
  1554. trouble=true;
  1555. }
  1556. else
  1557. {
  1558. DebugLog(@"move image folder successful");
  1559. }
  1560. error=nil;
  1561. // copy temp db to cache.
  1562. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1563. {
  1564. if(![fileManager removeItemAtPath:database_path error:nil])
  1565. {
  1566. DebugLog(@"delete database failed");
  1567. }
  1568. else
  1569. {
  1570. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1571. {
  1572. DebugLog(@"copy database failed");
  1573. [self add_downloadlog:@"copy database failed"];
  1574. trouble=true;
  1575. }
  1576. else{
  1577. //debug
  1578. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1579. [fileManager removeItemAtPath:tempdb error:nil];
  1580. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1581. }
  1582. }
  1583. }
  1584. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1585. {
  1586. DebugLog(@"copy database failed");
  1587. //debug;
  1588. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1589. [fileManager removeItemAtPath:tempdb error:nil];
  1590. [self add_downloadlog:@"copy database failed"];
  1591. trouble=true;
  1592. }
  1593. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1594. // {
  1595. // DebugLog(@"move db file failed");
  1596. // }
  1597. // else
  1598. // {
  1599. // DebugLog(@"move db file successful");
  1600. // }
  1601. error=nil;
  1602. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1603. {
  1604. DebugLog(@"move data folder failed");
  1605. [self add_downloadlog:@"move data folder failed"];
  1606. trouble=true;
  1607. }
  1608. else
  1609. {
  1610. DebugLog(@"move data folder successful");
  1611. }
  1612. dispatch_async(dispatch_get_main_queue(), ^{
  1613. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1614. });
  1615. if(trouble)
  1616. {
  1617. [self add_downloadlog:@"offline sync failed."];
  1618. // 尚缺更新失败还原逻辑。
  1619. }
  1620. else
  1621. {
  1622. [self add_downloadlog:@"offline sync complete."];
  1623. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1624. [defaults removeObjectForKey:@"OfflineVer"];
  1625. [defaults setValue:ver forKey:@"OfflineVer"];
  1626. [defaults removeObjectForKey:@"LastSync"];
  1627. [defaults setValue:lastsync forKey:@"LastSync"];
  1628. [defaults removeObjectForKey:@"vid"];
  1629. [defaults setValue:self.vid forKey:@"vid"];
  1630. [defaults removeObjectForKey:@"Forcedownload"];
  1631. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1632. [defaults removeObjectForKey:@"downSerial"];
  1633. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1634. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1635. [defaults synchronize];
  1636. NSString *plistPath = [RAUtils get_config_path];
  1637. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1638. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1639. {
  1640. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1641. [config_list writeToFile:plistPath atomically:YES];
  1642. }
  1643. [RANetwork request_complete_offline_ticket:downSerial completionHandler:^(NSMutableDictionary *result) {
  1644. }];
  1645. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1646. //
  1647. //
  1648. // //debug
  1649. //// NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
  1650. // [RANetwork finish_download_Offline:downSerial];
  1651. //
  1652. //
  1653. // });
  1654. }
  1655. dispatch_async(dispatch_get_main_queue(), ^{
  1656. // self.downloadlog=nil;
  1657. self.downloading=false;
  1658. self.download_task=nil;
  1659. self.vid=nil;
  1660. [self.settingUI onSyncFinish];
  1661. });
  1662. }
  1663. }
  1664. else
  1665. {
  1666. int count = [[self.download_task valueForKey:@"count"] intValue];
  1667. for (int i = 0;i<count;i++)
  1668. {
  1669. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1670. NSString* url = [itemjson valueForKey:@"url"];
  1671. NSString* type = [itemjson valueForKey:@"type"];
  1672. NSString* status = itemjson[@"status"];
  1673. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1674. if(! [status isEqualToString:@"finish"])
  1675. {
  1676. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1677. {
  1678. [self handle_download:url start:start type:type taskid:i];
  1679. break;
  1680. }
  1681. }
  1682. }
  1683. dispatch_async(dispatch_get_main_queue(), ^{
  1684. self.downloading=false;
  1685. });
  1686. }
  1687. }
  1688. -(void) add_downloadlog:(NSString*) newtext
  1689. {
  1690. // if(!self.downloading)
  1691. // return;
  1692. dispatch_async(dispatch_get_main_queue(), ^{
  1693. NSString* date;
  1694. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1695. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1696. date = [formatter stringFromDate:[NSDate date]];
  1697. if(newtext.length<=0)
  1698. return;
  1699. NSString* text = self.downloadlog;
  1700. if(text.length==0)
  1701. text=@"";
  1702. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1703. self.downloadlog = text;
  1704. [self.settingUI onLogUpdate];
  1705. });
  1706. }
  1707. -(int)unpack
  1708. {
  1709. //return;
  1710. //DebugLog(_fileName);
  1711. ///Users/Ray/Library/Developer/CoreSimulator/Devices/0852B217-599B-41C2-95BA-4755B02B7FA0/data/Containers/Data/Application/FC6AC5D0-2ADF-4A3B-935D-059078622031/Library/Caches/apache-tomcat-8.0.22.zip
  1712. //文件路径
  1713. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1714. NSString* temp = NSTemporaryDirectory();
  1715. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1716. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1717. NSString * ver = self.download_task[@"ver"];
  1718. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1719. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1720. ZipArchive* zip = [[ZipArchive alloc] init];
  1721. // filename stringByDeletingPathExtension
  1722. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1723. // NSString *cachefolder = [paths objectAtIndex:0];
  1724. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1725. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1726. //
  1727. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1728. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1729. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1730. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1731. DebugLog(@"path: %@",unZipTo);
  1732. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1733. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1734. if( NO==result )
  1735. {
  1736. // int aaa=0;
  1737. //解压失败
  1738. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1739. if(freespace<=10)
  1740. {
  1741. return UNZIP_NO_SPACE;
  1742. }
  1743. [zip UnzipCloseFile];
  1744. //文件损坏,删除文件重试
  1745. NSFileManager* fileManager=[NSFileManager defaultManager];
  1746. //debug
  1747. // BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1748. [fileManager removeItemAtPath:zipFile error:nil];
  1749. [fileManager removeItemAtPath:unZipTo error:nil];
  1750. return UNZIP_FILE_DAMAGE;
  1751. }
  1752. else
  1753. {
  1754. [zip UnzipCloseFile];
  1755. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1756. NSFileManager *fileManager = [NSFileManager defaultManager];
  1757. [fileManager removeItemAtPath:zipFile error:nil];
  1758. return UNZIP_SUCCESS;
  1759. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1760. }
  1761. //[zip UnzipCloseFile];
  1762. }
  1763. else
  1764. {
  1765. //打开文件失败,通常是文件路径有问题或密码错误。
  1766. return UNZIP_OPEN_FAILED;
  1767. // NSFileManager *fileManager = [NSFileManager defaultManager];
  1768. // [fileManager removeItemAtPath:zipFile error:nil];
  1769. }
  1770. // [zip release];
  1771. }
  1772. #pragma mark - NSURLConnectionDelegate
  1773. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1774. DebugLog(@"%d error message:%@",self.current_task,error);
  1775. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1776. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1777. currenttask[@"status"] = @"pause";
  1778. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1779. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1780. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1781. // self.currentLength = 0;
  1782. // self.fileLength = 0;
  1783. [self.fileHandle closeFile];
  1784. self.fileHandle = nil;
  1785. [self.connection cancel];
  1786. self.connection = nil;
  1787. [self download_offline:true checkdiskspace:false];
  1788. }
  1789. #pragma mark - NSURLConnectionDataDelegate
  1790. /**
  1791. *请求失败
  1792. */
  1793. /**
  1794. *接收到服务器的响应
  1795. */
  1796. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1797. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1798. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1799. DebugLog(@"%d begin",self.current_task);
  1800. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1801. //获取下载文件大小
  1802. // self.fileLength = response.expectedContentLength;
  1803. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1804. //获取文件名
  1805. //self.fileName = response.suggestedFilename;
  1806. currenttask[@"fileName"] = response.suggestedFilename;
  1807. currenttask[@"response"] = @"true";
  1808. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1809. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1810. //文件路径
  1811. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1812. NSString * ver = self.download_task[@"ver"];
  1813. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1814. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1815. DebugLog(@"save to: %@",filePath);
  1816. if (position>0) {
  1817. //不需要创建文件;
  1818. //创建一个用来写数据的文件句柄
  1819. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1820. return;
  1821. }
  1822. // 第一次获取的才是文件正确大小
  1823. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1824. //创建一个空的文件到沙盒
  1825. NSFileManager *fileManager = [NSFileManager defaultManager];
  1826. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1827. //创建一个用来写数据的文件句柄
  1828. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1829. }else{
  1830. //debug 这里缺少文件的情况还没处理
  1831. [self.connection cancel];
  1832. self.connection = nil;
  1833. DebugLog(@"该文件不存在");
  1834. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
  1835. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1836. [self add_downloadlog:str_status];
  1837. }
  1838. }
  1839. /**
  1840. *接收到服务器返回的数据(可能被调用多次)
  1841. */
  1842. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  1843. //移动到文件末尾
  1844. [self.fileHandle seekToEndOfFile];
  1845. //写入数据到文件
  1846. [self.fileHandle writeData:data];
  1847. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1848. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1849. position += data.length;
  1850. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  1851. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1852. //更新画面中的进度
  1853. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  1854. double progress = (double)position/fileLength;
  1855. self.file_progress = progress;
  1856. [self.settingUI onProgressUpdate];
  1857. }
  1858. /**
  1859. *服务器返回数据完了
  1860. */
  1861. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  1862. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1863. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  1864. DebugLog(@"%d finish",self.current_task);
  1865. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  1866. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1867. // self.currentLength = 0;
  1868. // self.fileLength = 0;
  1869. [self.fileHandle closeFile];
  1870. self.fileHandle = nil;
  1871. int result=[self unpack];
  1872. NSString* temp = NSTemporaryDirectory();
  1873. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1874. NSString * ver = self.download_task[@"ver"];
  1875. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1876. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1877. switch (result) {
  1878. case UNZIP_FILE_DAMAGE:
  1879. {
  1880. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1881. currenttask[@"status"] = @"pause";
  1882. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1883. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1884. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1885. // self.currentLength = 0;
  1886. // self.fileLength = 0;
  1887. [self.fileHandle closeFile];
  1888. self.fileHandle = nil;
  1889. [self.connection cancel];
  1890. self.connection = nil;
  1891. break;
  1892. }
  1893. case UNZIP_SUCCESS:
  1894. {
  1895. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  1896. if([type isEqualToString:@"img"])
  1897. {
  1898. NSString* parent_path = self.download_task[@"path"];
  1899. if(parent_path.length==0)
  1900. parent_path=@"";
  1901. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  1902. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  1903. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  1904. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1905. BOOL bdir=YES;
  1906. NSError *error = nil;
  1907. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  1908. {
  1909. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1910. if(!bsuccess)
  1911. DebugLog(@"Create temp folder failed");
  1912. }
  1913. error=nil;
  1914. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  1915. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  1916. // NSError *error = nil;
  1917. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  1918. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  1919. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  1920. // backupItemName:backup
  1921. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  1922. // resultingItemURL:nil error:&error])
  1923. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  1924. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  1925. {
  1926. DebugLog(@"move image folder failed");
  1927. }
  1928. else
  1929. {
  1930. currenttask[@"status"] = @"finish";
  1931. DebugLog(@"move image folder successful");
  1932. }
  1933. }
  1934. else if([type isEqualToString:@"sql"])
  1935. {
  1936. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1937. NSString * ver = self.download_task[@"ver"];
  1938. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  1939. tempdb=[temp stringByAppendingPathComponent:tempdb];
  1940. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  1941. [self add_downloadlog:@"updating local database..."];
  1942. @try {
  1943. char *errmsg=NULL;
  1944. // [iSalesDB disable_trigger]
  1945. [iSalesDB disable_trigger];
  1946. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  1947. {
  1948. sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;drop trigger if exists offline_pdf;", NULL, NULL, &errmsg);
  1949. sqlite3_free(errmsg);
  1950. DebugLog(@"开启事务");
  1951. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  1952. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  1953. int count = [orderjson[@"count"] intValue];
  1954. for(int i=0;i<count;i++)
  1955. {
  1956. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  1957. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  1958. NSError *error = nil;
  1959. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  1960. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  1961. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  1962. {
  1963. //throw exception;
  1964. if(errmsg==nil)
  1965. errmsg="Unknown error.";
  1966. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  1967. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  1968. }
  1969. sqlite3_free(errmsg);
  1970. }
  1971. sqlite3_exec(tdb, "CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
  1972. }
  1973. //提交事务
  1974. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  1975. DebugLog(@"提交事务");
  1976. sqlite3_free(errmsg);
  1977. }
  1978. [self add_downloadlog:@"updating local database successful"];
  1979. currenttask[@"status"] = @"finish";
  1980. }
  1981. @catch (NSException *exception) {
  1982. char *errmsg=NULL;
  1983. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  1984. [self add_downloadlog:@"updating local database failed rollback..."];
  1985. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  1986. DebugLog(@"回滚事务");
  1987. }
  1988. else
  1989. {
  1990. [self add_downloadlog:@"rollback failed."];
  1991. }
  1992. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1993. currenttask[@"status"] = @"pause";
  1994. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1995. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  1996. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1997. // self.currentLength = 0;
  1998. // self.fileLength = 0;
  1999. [self.fileHandle closeFile];
  2000. self.fileHandle = nil;
  2001. [self.connection cancel];
  2002. self.connection = nil;
  2003. //break;
  2004. }
  2005. @finally {
  2006. // [iSalesDB enable_trigger]
  2007. [iSalesDB enable_trigger];
  2008. sqlite3_close(tdb);
  2009. // [iSalesDB close_db:tdb];
  2010. // [self SelectData];
  2011. }
  2012. }
  2013. else if([type isEqualToString:@"script"])
  2014. {
  2015. currenttask[@"status"] = @"finish";
  2016. }
  2017. else if([type isEqualToString:@"resource"])
  2018. {
  2019. currenttask[@"status"] = @"finish";
  2020. }
  2021. // debug
  2022. // int c=self.current_task+1;
  2023. // double t=[ self.download_task[@"count"] doubleValue];
  2024. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  2025. self.overall_progress = oprogress;
  2026. [self.settingUI onProgressUpdate];
  2027. break;
  2028. }
  2029. case UNZIP_NO_SPACE:
  2030. {
  2031. [self add_downloadlog:@"Disk space not enough."];
  2032. break;
  2033. }
  2034. case UNZIP_OPEN_FAILED:
  2035. {
  2036. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  2037. break;
  2038. }
  2039. default:
  2040. break;
  2041. }
  2042. [self download_offline:true checkdiskspace:false];
  2043. }
  2044. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  2045. {
  2046. RAPDFViewController *ViewController = [[UIStoryboard storyboardWithName:@"wkweb" bundle:nil] instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  2047. ViewController.url = url;
  2048. ViewController.canSave = false;
  2049. ViewController.mail_content = content;
  2050. if(soid==nil)
  2051. soid =@"";
  2052. if(company==nil)
  2053. company =@"";
  2054. ViewController.save_name =soid;
  2055. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  2056. if(send_to.length>0)
  2057. {
  2058. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2059. // customer_email compo
  2060. // [send_to addObject:customer_email];
  2061. }
  2062. ViewController.mail_to = arrsend_to;
  2063. #if defined(BUILD_NPD) || defined(BUILD_USAI)|| defined (BUILD_CONTRAST)
  2064. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
  2065. if (self.user_type == USER_ROLE_CUSTOMER && ![RASingleton sharedInstance].currentOrderIsMerged) {
  2066. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2067. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2068. }
  2069. #else
  2070. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
  2071. #endif
  2072. ViewController.mail_subject = subject;
  2073. // NSString* subject;
  2074. // if (company.length==0) {
  2075. // NSString* cur_time =[RAUtils current_date];
  2076. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  2077. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2078. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  2079. //
  2080. //
  2081. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  2082. // if(customer_email.length>0)
  2083. // {
  2084. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2085. // // customer_email compo
  2086. // // [send_to addObject:customer_email];
  2087. // }
  2088. // ViewController.mail_to = send_to;
  2089. // }
  2090. // else
  2091. // {
  2092. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  2093. // }
  2094. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  2095. // ViewController.mail_subject = subject;
  2096. ViewController.autoPrint=true;
  2097. ViewController.hidenavi = false;
  2098. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  2099. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  2100. }
  2101. //-(void) addScannerReceiver:(NSString*)classname
  2102. //{
  2103. // [self.arr_scannerReceiver addObject:classname];
  2104. //}
  2105. -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
  2106. {
  2107. [ScanApi setDelegate:delegate];
  2108. }
  2109. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2110. {
  2111. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2112. // 蓝牙扫描枪
  2113. #ifdef USE_BLE_SCANNER
  2114. self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  2115. _cbReady = false;
  2116. _nDevices = [[NSMutableArray alloc]init];
  2117. _nServices = [[NSMutableArray alloc]init];
  2118. _nCharacteristics = [[NSMutableArray alloc]init];
  2119. self.bAutoConnect=[defaults boolForKey:@"BLE_AutoReconnect"];
  2120. self.bAppBTOn=[defaults boolForKey:@"BLE_Enable"];
  2121. if(self.bAutoConnect)
  2122. {
  2123. self.strDeviceName = [defaults valueForKey:@"BLE_Name"];
  2124. self.strDeviceUUID = [defaults valueForKey:@"BLE_UUID"];
  2125. }
  2126. #endif
  2127. // [defaults removeObjectForKey:@"BLE_AutoReconnect"];
  2128. #ifdef SCANNER_ORDER
  2129. //审核时连接测试数据库
  2130. // NSDate *cdate= [NSDate date];
  2131. // NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
  2132. // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
  2133. //
  2134. //NSDate * ddate =[dateFormatter dateFromString:@"2022-07-08"];
  2135. //
  2136. //// bool review=[cdate earlierDate:ddate];
  2137. // NSTimeInterval secondsInterval= [cdate timeIntervalSinceDate:ddate];
  2138. // int sec =secondsInterval;
  2139. bool rtime = [RADataProvider scanRtime];
  2140. NSDictionary *addressDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"ScanAddress"];
  2141. if(rtime && !addressDic)
  2142. {
  2143. NSUInteger selectedIndex = 1;
  2144. // 保存信息
  2145. NSString *name = @"HMLG";
  2146. NSString *show_name = @"FREMONT, CA";
  2147. NSString *internalAddr =@"https://erp.homelegance.com/" ;
  2148. int price_index = 0;
  2149. // NSString *externalAddr = weakself.externalTextField.text;
  2150. NSMutableDictionary *addressDic = [NSMutableDictionary dictionary];
  2151. if (internalAddr.length) {
  2152. [addressDic setObject:internalAddr forKey:@"serverAddress"];
  2153. }
  2154. // if (externalAddr.length) {
  2155. // [addressDic setObject:externalAddr forKey:@"externalAddress"];
  2156. // }
  2157. if (name.length) {
  2158. [addressDic setObject:name forKey:@"name"];
  2159. }
  2160. if (show_name.length) {
  2161. [addressDic setObject:show_name forKey:@"show_name"];
  2162. }
  2163. addressDic[@"has_erp_site"] = @(true);
  2164. [addressDic setObject:@(price_index) forKey:@"price_index"];
  2165. [addressDic setObject:@(selectedIndex) forKey:@"selectedIndex"];
  2166. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  2167. [userDefaults setValue:addressDic forKey:@"ScanAddress"];
  2168. [userDefaults synchronize];
  2169. }
  2170. self.compressFile = [[RAUPloadManagerConfigure alloc] init].compressImage;
  2171. #endif
  2172. //#ifdef OFFLINE_ORDER
  2173. //
  2174. //#endif
  2175. self.window.backgroundColor = [UIColor whiteColor];
  2176. // [RAUtils expression_varable:nil regex:nil];
  2177. // self.disable_trigger = false;
  2178. [iSalesDB enable_trigger];
  2179. [self initialExceptionHandler];
  2180. [self becomeObserver];
  2181. #ifdef GOOGLE_ANALYTICS
  2182. [self setUpGoogleAnalytics];
  2183. #endif
  2184. [DefaultAppearance init_appearance];
  2185. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2186. NSString *cachefolder = [paths objectAtIndex:0];
  2187. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  2188. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  2189. NSFileManager* fileManager = [NSFileManager defaultManager];
  2190. BOOL bdir=YES;
  2191. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  2192. {
  2193. NSError *error = nil;
  2194. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  2195. if(!bsuccess)
  2196. DebugLog(@"Create UPLOAD folder failed");
  2197. }
  2198. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  2199. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  2200. {
  2201. NSError *error = nil;
  2202. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  2203. if(!bsuccess)
  2204. DebugLog(@"Create PDF Cache folder failed");
  2205. }
  2206. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2207. //
  2208. // DebugLog(@"文件已经存在了");
  2209. //
  2210. // }
  2211. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  2212. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  2213. //
  2214. //
  2215. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2216. // NSString *documents = [paths objectAtIndex:0];
  2217. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  2218. //
  2219. //
  2220. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2221. //
  2222. // DebugLog(@"文件已经存在了");
  2223. //
  2224. // }
  2225. // else
  2226. // {
  2227. //
  2228. //
  2229. //
  2230. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  2231. //
  2232. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  2233. //
  2234. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  2235. //
  2236. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  2237. //
  2238. // contents:mainBundleFile
  2239. //
  2240. // attributes:nil];
  2241. //
  2242. // }
  2243. self.recent_model = [[NSMutableDictionary alloc]init];
  2244. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2245. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  2246. self.offline_mode = offline;
  2247. // Override point for customization after application launch.
  2248. if ( [iSalesDB initializeDb]!=0)
  2249. DebugLog(@"init db failed");
  2250. // disable apn
  2251. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  2252. self.contact_id=nil;
  2253. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2254. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  2255. if([enable_cache isEqualToString:@"false"])
  2256. self.bEnable_Cache = false;
  2257. else
  2258. self.bEnable_Cache = true;
  2259. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  2260. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  2261. //scanner
  2262. _feedbackStack=[[NSMutableArray alloc]init];
  2263. self.devices=[[NSMutableArray alloc]init];
  2264. // change this to YES if you want SingleEntry to
  2265. // confirm the decoded data
  2266. self.doAppDataConfirmation=NO;
  2267. if(ScanApi==nil){
  2268. #ifdef USE_SOFTSCAN
  2269. // this is useful for SoftScan to keep a handle
  2270. // that is used in the trigger button
  2271. _softScanDeviceInfo=nil;
  2272. #endif
  2273. ScanApi=[[ScanApiHelper alloc]init];
  2274. [ScanApi setDelegate:self];
  2275. self.enable_ScannerLog = true;
  2276. self.api_Status= API_STOP;
  2277. // UIApplication * app = [UIApplication sharedApplication];
  2278. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  2279. //
  2280. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2281. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  2282. if(autolaunch==true)
  2283. [self enableScanner:autolaunch];
  2284. }
  2285. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2286. [self handleErrorLog];
  2287. });
  2288. return YES;
  2289. }
  2290. #pragma mark - Feedback stack
  2291. -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
  2292. long index =[_feedbackStack indexOfObject:feedback];
  2293. if(index!=NSNotFound)
  2294. {
  2295. // if(index!=_feedbackStack.count-1)
  2296. // {
  2297. // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
  2298. // _eventsFeedback = feedback;
  2299. // }
  2300. }
  2301. else
  2302. {
  2303. [_feedbackStack addObject:feedback];
  2304. }
  2305. _eventsFeedback = feedback;
  2306. // if(_eventsFeedback != feedback){
  2307. // if(_eventsFeedback!=nil){
  2308. // [_feedbackStack addObject:_eventsFeedback];
  2309. // }
  2310. // _eventsFeedback=feedback;
  2311. //// [self generateDeviceArrivals];
  2312. // }
  2313. }
  2314. -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
  2315. [_feedbackStack removeObject:feedback];
  2316. if(_feedbackStack.count>0)
  2317. _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
  2318. else
  2319. _eventsFeedback = nil;
  2320. // if(_eventsFeedback ==feedback){
  2321. // if(_feedbackStack.count>0){
  2322. // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
  2323. // [_feedbackStack removeLastObject];
  2324. // _eventsFeedback = newDelegate;
  2325. // // generate a device Arrival for each scanner we've already receive
  2326. // // so that the new view can be aware of the connected scanners
  2327. //// [self generateDeviceArrivals];
  2328. // }
  2329. // else{
  2330. // _eventsFeedback=nil;
  2331. // }
  2332. // }
  2333. }
  2334. -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
  2335. {
  2336. _eventsFeedback = feedback;
  2337. }
  2338. #pragma mark - ScanApiHelper complete delegates
  2339. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  2340. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  2341. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  2342. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  2343. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  2344. // callback received when the Get Symbology Status is completed
  2345. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  2346. [self addlog:@"onGetSymbologyDpm:"];
  2347. SKTRESULT result=[[scanObj Msg]Result];
  2348. if(SKTSUCCESS(result)){
  2349. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  2350. if(deviceInfo!=nil){
  2351. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  2352. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  2353. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  2354. }
  2355. }
  2356. }
  2357. else{
  2358. // an error message should be displayed here
  2359. // indicating that the DPM symbology status cannot be retrieved
  2360. }
  2361. }
  2362. // callback received when the Set Symbology Status is completed
  2363. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  2364. [self addlog:@"onSetSymbology:"];
  2365. SKTRESULT result=[[scanObj Msg]Result];
  2366. if(!SKTSUCCESS(result)){
  2367. // display an error message saying a symbology cannot be set
  2368. }
  2369. }
  2370. /**
  2371. *
  2372. */
  2373. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  2374. [self addlog:@"onSetDataConfirmationMode:"];
  2375. SKTRESULT result=[[scanObj Msg]Result];
  2376. if(SKTSUCCESS(result)){
  2377. [self addlog:@"DataConfirmation Mode OK"];
  2378. }
  2379. else{
  2380. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  2381. }
  2382. }
  2383. /**
  2384. *
  2385. */
  2386. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  2387. [self addlog:@"onDataConfirmation:"];
  2388. SKTRESULT result=[[scanObj Msg]Result];
  2389. if(SKTSUCCESS(result)){
  2390. [self addlog:@"Data Confirmed OK"];
  2391. }
  2392. else{
  2393. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  2394. }
  2395. }
  2396. /**
  2397. *
  2398. */
  2399. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  2400. [self addlog:@"onSetLocalDecodeAction:"];
  2401. SKTRESULT result=[[scanObj Msg]Result];
  2402. if(SKTSUCCESS(result)){
  2403. [self addlog:@"Local Decode Action OK"];
  2404. }
  2405. else{
  2406. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  2407. }
  2408. }
  2409. /**
  2410. *
  2411. */
  2412. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  2413. SKTRESULT result=[[scanObj Msg]Result];
  2414. if(SKTSUCCESS(result)){
  2415. ISktScanProperty* property=[scanObj Property];
  2416. [self addlog:@"SoftScan status:"];
  2417. if([property getByte]==kSktScanEnableSoftScan){
  2418. [self addlog:@"SoftScan is ENABLED"];
  2419. _softScannerEnabled=TRUE;
  2420. }
  2421. else{
  2422. _softScannerEnabled=FALSE;
  2423. [self addlog:@"SoftScan is DISABLED"];
  2424. }
  2425. }
  2426. else{
  2427. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  2428. }
  2429. }
  2430. /**
  2431. *
  2432. */
  2433. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2434. [self addlog:@"onSetSoftScanStatus:"];
  2435. SKTRESULT result=[[scanObj Msg]Result];
  2436. if(SKTSUCCESS(result)){
  2437. [self addlog:@"SoftScan set status success"];
  2438. }
  2439. else{
  2440. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2441. }
  2442. }
  2443. /**
  2444. *
  2445. */
  2446. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2447. [self addlog:@"onSetTrigger:"];
  2448. SKTRESULT result=[[scanObj Msg]Result];
  2449. if(SKTSUCCESS(result)){
  2450. [self addlog:@"Trigger set success"];
  2451. }
  2452. else{
  2453. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2454. }
  2455. }
  2456. /**
  2457. *
  2458. */
  2459. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2460. [self addlog:@"onGetScanApiVersion:"];
  2461. SKTRESULT result=[[scanObj Msg]Result];
  2462. if(SKTSUCCESS(result))
  2463. {
  2464. ISktScanProperty*property=[scanObj Property];
  2465. if([property getType]==kSktScanPropTypeVersion)
  2466. {
  2467. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2468. [[property Version]getMajor],
  2469. [[property Version]getMiddle],
  2470. [[property Version]getMinor],
  2471. [[property Version]getBuild]];
  2472. }
  2473. }
  2474. else{
  2475. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2476. }
  2477. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2478. }
  2479. /**
  2480. *
  2481. */
  2482. #ifdef USE_SOFTSCAN
  2483. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2484. SKTRESULT result=[[scanObj Msg]Result];
  2485. if(SKTSUCCESS(result)){
  2486. [self addlog:@"Overlay view set success"];
  2487. }
  2488. else{
  2489. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2490. }
  2491. }
  2492. #endif
  2493. /**
  2494. * called each time a device connects to the host
  2495. * @param result contains the result of the connection
  2496. * @param newDevice contains the device information
  2497. */
  2498. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2499. [self addlog:@"onDeviceArrival:"];
  2500. [self updateDevicesList:deviceInfo Add:YES];
  2501. #ifdef USE_SOFTSCAN
  2502. // if the scanner is a SoftScan scanner
  2503. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2504. // _softScannerTriggerBtn.hidden=NO;
  2505. _softScanDeviceInfo=deviceInfo;
  2506. if(_deviceInfoToTrigger==nil)
  2507. _deviceInfoToTrigger=deviceInfo;
  2508. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2509. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2510. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2511. }
  2512. else
  2513. #endif
  2514. {
  2515. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2516. // _softScannerTriggerBtn.hidden=NO;
  2517. _deviceInfoToTrigger=deviceInfo;
  2518. }
  2519. if(_doAppDataConfirmation==YES){
  2520. // switch the comment between the 2 following lines for handling the
  2521. // data confirmation beep from the scanner (local)
  2522. // if none is set, the scanner will beep only once when SingleEntry actually
  2523. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2524. // and one when SingleEntry will confirm the decoded data
  2525. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2526. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2527. }
  2528. // for demonstration only, let's make sure the DPM is enabled
  2529. // first interrogate the scanner to see if it's already enabled
  2530. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2531. // then we send a Symbology property to enable it.
  2532. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2533. }
  2534. }
  2535. /**
  2536. * called each time a device disconnect from the host
  2537. * @param deviceRemoved contains the device information
  2538. */
  2539. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2540. [self addlog:@"onDeviceRemoval:"];
  2541. [self updateDevicesList:deviceRemoved Add:NO];
  2542. if(_deviceInfoToTrigger==deviceRemoved){
  2543. _deviceInfoToTrigger=nil;
  2544. }
  2545. #ifdef USE_SOFTSCAN
  2546. if(_softScanDeviceInfo==deviceRemoved){
  2547. _softScanDeviceInfo=nil;
  2548. }
  2549. if(_deviceInfoToTrigger==nil)
  2550. _deviceInfoToTrigger=_softScanDeviceInfo;
  2551. #endif
  2552. if(_deviceInfoToTrigger==nil){
  2553. // _softScannerTriggerBtn.hidden=YES;
  2554. }
  2555. }
  2556. /**
  2557. * called each time ScanAPI is reporting an error
  2558. * @param result contains the error code
  2559. */
  2560. -(void) onError:(SKTRESULT) result{
  2561. [self addlog:@"onError:"];
  2562. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2563. #ifdef RA_NOTIFICATION
  2564. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2565. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2566. }
  2567. #else
  2568. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2569. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2570. #endif
  2571. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2572. }
  2573. /**
  2574. * called each time ScanAPI receives decoded data from scanner
  2575. * @param deviceInfo contains the device information from which
  2576. * the data has been decoded
  2577. * @param decodedData contains the decoded data information
  2578. */
  2579. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2580. [self addlog:@"onDecodedDataResult:"];
  2581. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2582. if(SKTSUCCESS(result)){
  2583. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2584. #ifdef RA_NOTIFICATION
  2585. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2586. [_eventsFeedback onDecodedData:cleanString];
  2587. }
  2588. #else
  2589. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2590. [avc onDecodedData:cleanString];
  2591. #endif
  2592. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2593. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2594. if(_doAppDataConfirmation==YES){
  2595. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2596. }
  2597. }
  2598. }
  2599. -(void) test_onDecodedDataResult:(NSString*) value
  2600. {
  2601. [self addlog:@"onDecodedDataResult:"];
  2602. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2603. if(true){
  2604. #ifdef RA_NOTIFICATION
  2605. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2606. [_eventsFeedback onDecodedData:value];
  2607. }
  2608. #else
  2609. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2610. [avc onDecodedData:value];
  2611. #endif
  2612. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2613. [self addlog:value];
  2614. // if(_doAppDataConfirmation==YES){
  2615. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2616. // }
  2617. }
  2618. }
  2619. //-(void) didRotated
  2620. //{
  2621. //
  2622. //}
  2623. /**
  2624. * called when ScanAPI initialization has been completed
  2625. * @param result contains the initialization result
  2626. */
  2627. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2628. [self addlog:@"onScanApiInitializeComplete:"];
  2629. if(SKTSUCCESS(result))
  2630. {
  2631. self.api_Status = API_START;
  2632. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2633. [self addlog:strlog];
  2634. #ifdef USE_SOFTSCAN
  2635. // make sure we support SoftScan
  2636. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2637. // check if SoftScan is enabled
  2638. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2639. #else
  2640. // disable support SoftScan (Default, not really needed if it was never activated)
  2641. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2642. #endif
  2643. // ask for ScanAPI version (not a requirement but always nice to know)
  2644. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2645. // configure ScanAPI for doing App Data confirmation,
  2646. // if TRUE then SingleEntry will confirm the decoded data
  2647. if(_doAppDataConfirmation==YES){
  2648. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2649. }
  2650. #ifdef RA_NOTIFICATION
  2651. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2652. [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
  2653. }
  2654. #else
  2655. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2656. [avc onStatusChanged:@"Waiting for scanner..."];
  2657. #endif
  2658. self.Status_Text = @"Waiting for scanner...";
  2659. // _Status.text=@"Waiting for scanner...";
  2660. }
  2661. else{
  2662. #ifdef RA_NOTIFICATION
  2663. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2664. [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2665. }
  2666. #else
  2667. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2668. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2669. #endif
  2670. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2671. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2672. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2673. [self addlog:strlog];
  2674. }
  2675. }
  2676. /**
  2677. * called when ScanAPI has been terminated. This will be
  2678. * the last message received from ScanAPI
  2679. */
  2680. -(void) onScanApiTerminated{
  2681. [self addlog:@"onScanApiTerminated:"];
  2682. [ScanApiConsumer invalidate];
  2683. ScanApiConsumer= nil;
  2684. [self addlog:@"ScanApiConsumer invalidate"];
  2685. self.api_Status = API_STOP;
  2686. #ifdef RA_NOTIFICATION
  2687. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2688. [_eventsFeedback onStatusChanged:@"Off"];
  2689. }
  2690. #else
  2691. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2692. [avc onStatusChanged:@"Off"];
  2693. #endif
  2694. self.Status_Text =@"Off";
  2695. // _Status.text = @"Off";
  2696. }
  2697. /**
  2698. * called when an error occurs during the retrieval
  2699. * of a ScanObject from ScanAPI.
  2700. * @param result contains the retrieval error code
  2701. */
  2702. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2703. [self addlog:@"onErrorRetrievingScanObject:"];
  2704. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2705. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2706. #ifdef RA_NOTIFICATION
  2707. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2708. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2709. }
  2710. #else
  2711. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2712. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2713. #endif
  2714. }
  2715. #pragma mark - Scaner
  2716. -(void)onTimer: (NSTimer*)theTimer{
  2717. if(theTimer==ScanApiConsumer){
  2718. // [self addlog:@"ScanApi::doScanApiReceive:"];
  2719. [ScanApi doScanApiReceive];
  2720. }
  2721. }
  2722. -(void) addlog:(NSString*) newtext
  2723. {
  2724. if(!self.enable_ScannerLog)
  2725. return;
  2726. dispatch_async(dispatch_get_main_queue(), ^{
  2727. NSString* date;
  2728. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  2729. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  2730. date = [formatter stringFromDate:[NSDate date]];
  2731. if(newtext.length<=0)
  2732. return;
  2733. NSString* text = self.log;
  2734. if(text.length==0)
  2735. text=@"";
  2736. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  2737. self.log = text;
  2738. #ifdef RA_NOTIFICATION
  2739. if((self->_eventsFeedback!=nil)&&([self->_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
  2740. [self->_eventsFeedback onLogUpdate];
  2741. }
  2742. #else
  2743. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2744. [avc onLogUpdate];
  2745. #endif
  2746. });
  2747. }
  2748. - (void)enableScanner:(bool)enable {
  2749. [self addlog:@"Enable scanner:"];
  2750. if(enable)
  2751. {
  2752. [self addlog:@"Enable"];
  2753. self.api_Status = API_INIT;
  2754. #ifdef RA_NOTIFICATION
  2755. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2756. [_eventsFeedback onStatusChanged:@"Initialize..."];
  2757. }
  2758. #else
  2759. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2760. [avc onStatusChanged:@"Initialize..."];
  2761. #endif
  2762. self.Status_Text = @"Initialize...";
  2763. [ScanApi open];
  2764. [self addlog:@"ScanApi open"];
  2765. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  2766. [self addlog:@"ScanApiConsumer init"];
  2767. // [ScanApi close];
  2768. // [self addlog:@"ScanApi opent"];
  2769. }
  2770. else
  2771. {
  2772. [self addlog:@"Disable"];
  2773. // [ScanApiConsumer invalidate];
  2774. // ScanApiConsumer= nil;
  2775. // [self addlog:@"ScanApiConsumer invalidate"];
  2776. self.api_Status = API_CLOSING;
  2777. #ifdef RA_NOTIFICATION
  2778. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2779. [_eventsFeedback onStatusChanged:@"Stoping..."];
  2780. }
  2781. #else
  2782. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2783. [avc onStatusChanged:@"Stoping..."];
  2784. #endif
  2785. self.Status_Text = @"Stoping...";
  2786. [ScanApi close];
  2787. [self addlog:@"ScanApi close"];
  2788. }
  2789. }
  2790. #pragma mark - Device Info List management
  2791. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  2792. [self addlog:@"updateDevicesList:"];
  2793. if(add==YES){
  2794. [self.devices addObject:deviceInfo];
  2795. }
  2796. else{
  2797. [self.devices removeObject:deviceInfo];
  2798. }
  2799. NSMutableString* temp=[[NSMutableString alloc]init];
  2800. for (DeviceInfo* info in self.devices) {
  2801. [temp appendString:[info getName]];
  2802. [temp appendString:@"\n"];
  2803. }
  2804. if(self.devices.count>0)
  2805. [temp appendString:@"ready to scan"];
  2806. else
  2807. [temp appendString:@"Waiting for Scanner..."];
  2808. // _Status.text=temp ;
  2809. [self addlog:temp];
  2810. #ifdef RA_NOTIFICATION
  2811. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2812. [_eventsFeedback onStatusChanged:temp];
  2813. }
  2814. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2815. [_eventsFeedback OnUpdateDevicesList];
  2816. }
  2817. #else
  2818. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2819. [avc onStatusChanged:temp];
  2820. [avc OnUpdateDevicesList];
  2821. #endif
  2822. self.Status_Text = temp;
  2823. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  2824. // [self.dev_table reloadData];
  2825. }
  2826. #pragma mark - offline order
  2827. -(void) backup_oc
  2828. {
  2829. }
  2830. -(void) restore_oc
  2831. {
  2832. }
  2833. #ifdef SCANNER_ORDER
  2834. #pragma mark - upload manager
  2835. - (void)saveUploadTasks {
  2836. if(true)
  2837. {
  2838. if(self.uploadManager.arr_queue!=nil)
  2839. {
  2840. [self.uploadManager stopAllTasks];
  2841. }
  2842. [self.uploadManager saveTasks];
  2843. return;
  2844. }
  2845. }
  2846. - (NSMutableArray *)cachedUploadTasks {
  2847. if (!self.user) {
  2848. return nil;
  2849. }
  2850. NSString *path = [[RAUtils appCacheDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_uploadTasks",self.user]];
  2851. NSFileManager *manager = [NSFileManager defaultManager];
  2852. if ([manager fileExistsAtPath:path]) {
  2853. NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
  2854. [manager removeItemAtPath:path error:nil];
  2855. return arr;
  2856. }
  2857. return nil;
  2858. }
  2859. #endif
  2860. #ifdef USE_BLE_SCANNER
  2861. #pragma mark - core bluetooth
  2862. -(void) disconnectDevice
  2863. {
  2864. if(self.peripheral)
  2865. [self.manager cancelPeripheralConnection:self.peripheral];
  2866. if( self.bAppBTOn ==true)
  2867. [self scanBLE];
  2868. }
  2869. -(void)setBLEAutoReconnect:(bool) bAutoReconnect
  2870. {
  2871. self.bAutoConnect = true;
  2872. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2873. [defaults removeObjectForKey:@"BLE_Name"];
  2874. [defaults removeObjectForKey:@"BLE_UUID"];
  2875. [defaults removeObjectForKey:@"BLE_AutoReconnect"];
  2876. if(bAutoReconnect&&self.peripheral)
  2877. {
  2878. [defaults setValue:self.peripheral.name forKey: @"BLE_Name"];
  2879. [defaults setValue:self.peripheral.identifier.UUIDString forKey: @"BLE_UUID"];
  2880. }
  2881. else
  2882. {
  2883. self.strDeviceName = nil;
  2884. self.strDeviceUUID=nil;
  2885. }
  2886. [defaults setBool:bAutoReconnect forKey:@"BLE_AutoReconnect"];
  2887. [defaults synchronize];
  2888. }
  2889. -(void) enableBLE:(bool) bEnable
  2890. {
  2891. self.bAppBTOn =bEnable;
  2892. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2893. [defaults removeObjectForKey:@"BLE_Enable"];
  2894. [defaults setBool:self.bAppBTOn forKey:@"BLE_Enable"];
  2895. [defaults synchronize];
  2896. if(bEnable)
  2897. [self scanBLE];
  2898. else
  2899. [self stopScanBLE];
  2900. }
  2901. -(void) scanBLE
  2902. {
  2903. switch (self.manager.state) {
  2904. case CBManagerStatePoweredOn:
  2905. {
  2906. [self updateLog:@"Scanning..."];
  2907. [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
  2908. // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
  2909. }
  2910. break;
  2911. case CBManagerStatePoweredOff:
  2912. [self updateLog:@"Please turn on bluetooth。"];
  2913. break;
  2914. default:
  2915. break;
  2916. }
  2917. }
  2918. -(void) stopScanBLE
  2919. {
  2920. // self.bAppBTOn = false;
  2921. [self.manager stopScan];
  2922. if(self.self.peripheral)
  2923. [self.manager cancelPeripheralConnection:self.peripheral];
  2924. self.nDevices = [NSMutableArray new];
  2925. self.peripheral = nil;
  2926. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2927. [_eventsFeedback OnUpdateDevicesList];
  2928. }
  2929. }
  2930. //检查蓝牙状态
  2931. - (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
  2932. switch (central.state) {
  2933. case CBManagerStatePoweredOn:
  2934. {
  2935. [self updateLog:@"Bluetooth on."];
  2936. self.bBTAuthorize = true;
  2937. if(self.bAppBTOn)
  2938. {
  2939. [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
  2940. }
  2941. // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
  2942. }
  2943. break;
  2944. case CBManagerStatePoweredOff:
  2945. [self updateLog:@"Bluetooth off."];
  2946. self.bBTAuthorize = true;
  2947. break;
  2948. case CBManagerStateUnauthorized:
  2949. //蓝牙未授权
  2950. // app一定未授权,蓝牙是否开启不知
  2951. [self updateLog:@"Bluetooth Unauthorized."];
  2952. self.bBTAuthorize = false;
  2953. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2954. [_eventsFeedback onStatusChanged:@"Unauthorized"];
  2955. }
  2956. break;
  2957. default:
  2958. break;
  2959. }
  2960. }
  2961. -(void)updateLog:(NSString*) log
  2962. {
  2963. // NSLog(log);
  2964. //
  2965. // self.strBTLog=[self.strBTLog stringByAppendingString:[log stringByAppendingString:@"\n"]];
  2966. [self addlog:log];
  2967. }
  2968. //查到外设后,停止扫描,连接设备
  2969. -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  2970. {
  2971. // NSLog(@"didDiscoverPeripheral");
  2972. NSArray* pservice = advertisementData[@"kCBAdvDataServiceUUIDs"];
  2973. if(pservice.count<=0)
  2974. return;
  2975. if(peripheral.name.length<=0)
  2976. return;
  2977. // _peripheral = peripheral;
  2978. // [_manager connectPeripheral:_peripheral options:nil];
  2979. // [self.manager stopScan];
  2980. // [_activity stopAnimating];
  2981. BOOL replace = NO;
  2982. // Match if we have this device from before
  2983. for (int i=0; i < _nDevices.count; i++) {
  2984. CBPeripheral *p = [_nDevices objectAtIndex:i];
  2985. if ([p isEqual:peripheral]) {
  2986. [_nDevices replaceObjectAtIndex:i withObject:peripheral];
  2987. replace = YES;
  2988. }
  2989. }
  2990. if (!replace) {
  2991. [_nDevices addObject:peripheral];
  2992. [self updateLog:[NSString stringWithFormat:@"Found device: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.identifier, advertisementData]];
  2993. }
  2994. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2995. [_eventsFeedback OnUpdateDevicesList];
  2996. }
  2997. if(self.bAutoConnect&& [self.strDeviceUUID isEqualToString:peripheral.identifier.UUIDString])
  2998. {
  2999. self.peripheral = peripheral;
  3000. NSString* log = [NSString stringWithFormat:@"Reconnect to device %@ ...", peripheral.name];
  3001. [self updateLog:log];
  3002. NSLog(@"Retrying");
  3003. [self.manager connectPeripheral:peripheral options:nil];
  3004. }
  3005. // if(peripheral.identifier == self.peripheral.identifier)
  3006. // {
  3007. // //重新连接
  3008. // [_manager connectPeripheral:_peripheral options:nil];
  3009. // }
  3010. //[_bluetoothTable reloadData];
  3011. }
  3012. //连接外设成功,开始发现服务
  3013. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
  3014. NSLog(@"%@", [NSString stringWithFormat:@"成功连接 peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]);
  3015. [self updateLog:[NSString stringWithFormat:@"Connect peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]];
  3016. [self.peripheral setDelegate:self];
  3017. [self.peripheral discoverServices:nil];
  3018. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  3019. [_eventsFeedback onStatusChanged:@"Connected"];
  3020. }
  3021. // [self updateLog:@"扫描服务"];
  3022. }
  3023. //连接外设失败
  3024. -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  3025. {
  3026. NSLog(@"%@",error);
  3027. [self updateLog:@"Failed to connect device."];
  3028. }
  3029. -(void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
  3030. {
  3031. NSLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);
  3032. int rssi = abs([peripheral.RSSI intValue]);
  3033. CGFloat ci = (rssi - 49) / (10 * 4.);
  3034. NSString *length = [NSString stringWithFormat:@"Found hotpoint:%@,distence:%.1fm",_peripheral,pow(10,ci)];
  3035. [self updateLog:[NSString stringWithFormat:@"Distence:%@", length]];
  3036. }
  3037. //已发现服务
  3038. -(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
  3039. [self updateLog:@"Found service."];
  3040. int i=0;
  3041. for (CBService *s in peripheral.services) {
  3042. [self.nServices addObject:s];
  3043. }
  3044. for (CBService *s in peripheral.services) {
  3045. [self updateLog:[NSString stringWithFormat:@"%d :service UUID: %@(%@)",i,s.UUID.data,s.UUID]];
  3046. i++;
  3047. [peripheral discoverCharacteristics:nil forService:s];
  3048. // if ([s.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]])
  3049. // {
  3050. // BOOL replace = NO;
  3051. // // Match if we have this device from before
  3052. // for (int i=0; i < _nDevices.count; i++) {
  3053. // CBPeripheral *p = [_nDevices objectAtIndex:i];
  3054. // if ([p isEqual:peripheral]) {
  3055. // [_nDevices replaceObjectAtIndex:i withObject:peripheral];
  3056. // replace = YES;
  3057. // }
  3058. // }
  3059. // if (!replace) {
  3060. // [_nDevices addObject:peripheral];
  3061. //// [_bluetoothTable reloadData];
  3062. // }
  3063. // }
  3064. }
  3065. }
  3066. //已搜索到Characteristics
  3067. -(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
  3068. [self updateLog:[NSString stringWithFormat:@"service:%@ (%@)",service.UUID.data ,service.UUID]];
  3069. for (CBCharacteristic *c in service.characteristics)
  3070. {
  3071. [self updateLog:[NSString stringWithFormat:@"Characteristic UUID: %@ (%@)",c.UUID.data,c.UUID]];
  3072. if(c.properties& CBCharacteristicPropertyWrite) //写
  3073. // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]])
  3074. {
  3075. _writeCharacteristic = c;
  3076. }
  3077. if (c.properties&CBCharacteristicPropertyNotify) // 通知
  3078. // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]])
  3079. {
  3080. [_peripheral readValueForCharacteristic:c];
  3081. [_peripheral setNotifyValue:YES forCharacteristic:c];
  3082. }
  3083. }
  3084. }
  3085. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
  3086. [self updateLog:[NSString stringWithFormat:@"Disconnect device:[%@]", peripheral.name]];
  3087. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  3088. [_eventsFeedback onStatusChanged:@"Disconnected"];
  3089. }
  3090. if ([self.peripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
  3091. [self updateLog:@"Retrying..."];
  3092. NSLog(@"Retrying");
  3093. [self.manager connectPeripheral:peripheral options:nil];
  3094. }
  3095. }
  3096. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  3097. {
  3098. NSLog(@"didUpdateValueForCharacteristic from Characteristic %@",characteristic.UUID);
  3099. NSData * data = characteristic.value;
  3100. NSString *datastring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  3101. // NSString *datastring1 = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
  3102. // NSString *datastring2 = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
  3103. // NSString *datastring3 = [[NSString alloc] initWithData:data encoding:NSUTF32StringEncoding];
  3104. //
  3105. // = 1, /* 0..127 only */
  3106. // NSNEXTSTEPStringEncoding = 2,
  3107. // NSJapaneseEUCStringEncoding = 3,
  3108. //
  3109. // NSISOLatin1StringEncoding = 5,
  3110. // NSSymbolStringEncoding = 6,
  3111. // NSNonLossyASCIIStringEncoding = 7,
  3112. // NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
  3113. // NSISOLatin2StringEncoding = 9,
  3114. // NSUnicodeStringEncoding = 10,
  3115. // NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
  3116. // NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
  3117. // NSWindowsCP1253StringEncoding = 13, /* Greek */
  3118. // NSWindowsCP1254StringEncoding = 14, /* Turkish */
  3119. // NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
  3120. // NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
  3121. // NSMacOSRomanStringEncoding = 30,
  3122. //
  3123. // /* An alias for NSUnicodeStringEncoding */
  3124. //
  3125. // NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
  3126. // NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
  3127. //
  3128. // NSUTF32StringEncoding = 0x8c000100,
  3129. // NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
  3130. // NSUTF32LittleEndianStringEncoding = 0x9c000100
  3131. //
  3132. datastring = [datastring stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  3133. if(datastring.length==0)
  3134. {
  3135. NSLog(@"Scan Data is empty");
  3136. return;
  3137. }
  3138. else
  3139. NSLog(@"Scan value %@",datastring);
  3140. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  3141. [_eventsFeedback onDecodedData:datastring];
  3142. }
  3143. [self addlog:datastring];
  3144. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF02"]]) {
  3145. // NSData * data = characteristic.value;
  3146. // Byte * resultByte = (Byte *)[data bytes];
  3147. // for(int i=0;i<[data length];i++)
  3148. // printf("testByteFF02[%d] = %d\n",i,resultByte[i]);
  3149. // if (resultByte[1] == 0) {
  3150. // }else if (resultByte[1] == 1) {
  3151. // [self updateLog:@"未知错误"];
  3152. // }else if (resultByte[1] == 2) {
  3153. // [self updateLog:@"鉴权失败"];
  3154. // }
  3155. // }
  3156. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF04"]]) {
  3157. // NSData * data = characteristic.value;
  3158. // Byte * resultByte = (Byte *)[data bytes];
  3159. // for(int i=0;i<[data length];i++)
  3160. // printf("testByteFF04[%d] = %d\n",i,resultByte[i]);}
  3161. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF05"]]) {
  3162. // NSData * data = characteristic.value;
  3163. // Byte * resultByte = (Byte *)[data bytes];
  3164. // for(int i=0;i<[data length];i++)
  3165. // printf("testByteFF05[%d] = %d\n",i,resultByte[i]);
  3166. // if (resultByte[0] == 0) {
  3167. // // 设备加解锁状态 0 撤防 1 设防
  3168. // [self updateLog:@"当前车辆撤防状态"];
  3169. // }else if (resultByte[0] == 1) {
  3170. // // 设备加解锁状态 0 撤防 1 设防
  3171. // [self updateLog:@"当前车辆设防状态"];
  3172. // }
  3173. // }
  3174. }
  3175. //中心读取外设实时数据
  3176. - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
  3177. if (error) {
  3178. NSLog(@"Error changing notification state: %@", error.localizedDescription);
  3179. }
  3180. // Notification has started
  3181. if (characteristic.isNotifying) {
  3182. [peripheral readValueForCharacteristic:characteristic];
  3183. } else { // Notification has stopped
  3184. // so disconnect from the peripheral
  3185. NSLog(@"Notification stopped on %@. Disconnecting", characteristic);
  3186. [self updateLog:[NSString stringWithFormat:@"Notification stopped on %@. Disconnecting", characteristic]];
  3187. [self.manager cancelPeripheralConnection:self.peripheral];
  3188. }
  3189. }
  3190. //用于检测中心向外设写数据是否成功
  3191. -(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  3192. {
  3193. if (error) {
  3194. NSLog(@"=======%@",error.userInfo);
  3195. [self updateLog:[RAConvertor dict2string:error.userInfo]];
  3196. }else{
  3197. NSLog(@"发送数据成功");
  3198. [self updateLog:@"Send data."];
  3199. }
  3200. /* When a write occurs, need to set off a re-read of the local CBCharacteristic to update its value */
  3201. [peripheral readValueForCharacteristic:characteristic];
  3202. }
  3203. #endif
  3204. //
  3205. ////#parammark tableview
  3206. //
  3207. //- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  3208. // return self.nDevices.count;
  3209. //}
  3210. //
  3211. //- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  3212. // static NSString *CellIdentifier = @"Cell";
  3213. // // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  3214. // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  3215. // if (!cell) {
  3216. // cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  3217. // }
  3218. //
  3219. // CBPeripheral *p=self.nDevices[indexPath.item];
  3220. // NSString* name = p.name;
  3221. // if(name.length==0)
  3222. // name=@"NO Name";
  3223. // cell.textLabel.text = name;
  3224. //
  3225. // return cell;
  3226. //}
  3227. //-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3228. //{
  3229. // CBPeripheral *p=self.nDevices[indexPath.item];
  3230. //
  3231. // _peripheral = p;
  3232. // [_manager connectPeripheral:_peripheral options:nil];
  3233. //}
  3234. @end